1. 程式人生 > >數據庫學習筆記3 基本的查詢流 2

數據庫學習筆記3 基本的查詢流 2

學習筆記 ast 裏的 cti post pla 排序 ace 數據庫

order by子句對查詢結果集進行排序

  • 多列和拼接

多列的方式就很簡單了

select firstname,lastname 
from person.person
order by lastname,firstname;

這句話表示根據lastnamefirstname兩列進行排序,並且是先按照lastname進行排序如果有相同的值就按照firstname進行排序。

拼接很有意思,可以寫成這個樣子

select 
lastname+‘,‘+firstname as fullname
from person.person
order by lastname+‘,‘+firstname;

這是把表達式放在了order by子句中了,當然也可以把order by子句中的表達式換成select子句中的別名fullname

另外還有一種寫法是把列的位置寫在order by子句中,還不是很了解這樣寫法的目的,之後應該有更加詳細的講解。

  • 可以使用case

select description,len(description) as textlength from production.productdescription where description like ‘replacement%‘ order by case when left(Description,5)=‘This ‘ then stuff(description,1,5,‘‘) else description end;


這句話的意思是根據description排序,case的作用是如果description值得第一個單詞是This就把它截掉。

top謂詞

我印象中top的作用很小,也就是查詢某一個表裏的前幾條數據,但是這次知道了還有percentwith ties的存在

  • percent

遇到求百分比結果集的時候可以把top和percent連用

select top(3) percent ... from ....

這樣的寫法是表示查詢前百分之30的數據。

  • with ties

應對查詢成績前三名的同學如果簡單的使用 select top(3) ... from 這樣的句式其實是有問題的,如果滿足條件的數據不只三條,比如說有好幾個人並列第三。with ties

就是來解決這個問題的。

select top(3) with ties ...from ...

這樣的寫法表示,如果最後一條有滿足條件的數據也包含在查詢結果裏,所以最終查出來的結果並不一定是3條數據。

數據庫學習筆記3 基本的查詢流 2