1.sql語句查詢順序
select ...
from ...
where ...
group by ...
having ...
order by ...
sql語句執行順序
from
where
group by
having
select
over
distinct
top
order by
注意:1.如果引用不在group by清單中出現的屬性,而且也沒有将其作為group by子句之後的任何子句中聚合函數的輸入,sql server引擎将會報錯
2.支援order by子句指定沒有在select子句中出現過的元素,但是,如果指定了distinct後,order by子句就被限制為隻能選取在select清單中出現的那些元素。
2.over支援的四種排名函數:row_number、rank、dense_rank、ntile
select orderid,custid,val,
row_number() over(order by val) as rownum,
rank() over(order by val) as rank,
dense_rank() over(order by val) as dense_rank,
ntile(1000) over(order by val) as ntile
from salas.ordervalues
order by val;
看下差別:row_number 所有的資料順序排序
rank 順序排序,遇到同名的,則相同排名,會空出下一個排名
dense_rank 順序排序,遇到同名的,則相同排名,但不會空出下一個排名
ntile 将所有的瞬間按順序劃分為幾塊,每一塊進行排序
查詢效果示例:

3.運算符優先級:
1、()
2、 *、/、%
3、 +、-
4、比較運算符
5、not
6、and
7、between、in、like、or
8、=
4.CASE表達式:
示例:
case IsDeleted
when 1 then '已删除'
when 0 then '未删除'
else ''
end as idName,
case
when id < 100 then 'less then 100'
when id between 100 and 300 then 'between 100 and 300'
when id > 300 then 'more then 300'
else 'unknown'
end as idType
from dbo.SystemUsers
order by UserName;
5.join(ANSI标準)
JOIN 三種聯接:
交叉聯接---笛卡爾積 cross join
内聯接---笛卡爾積、過濾 inner join
外聯接---笛卡爾積、過濾、添加外部行 left outer join
6.使用PIVOT運算符進行透視轉換
select SalaryPayingEmployeeId, [300], [301],[302] from
(select SalaryPayingEmployeeId,costtype,cost from SalaryPayingItems
where IsDeleted=0 and SalaryPayingEmployeeId='45D0BE76-AC43-4942-9D5B-AA4DDA86BAD7') tspipivot
Pivot(sum( tspipivot.cost) for tspipivot.costtype in ([300],[301],[302])
) as tspipivot
7.使用unpivot運算符進行逆透視轉換
select SalaryPayingEmployeeId,costType,cost
from #temp
unpivot(cost for costType in([300],[301],[302])) as U;
示例:采用剛才轉換後的表再轉回去
8.臨時表
可以使用臨時表的場合:
1、需要把中間結果臨時儲存起來,以供以後查詢這些臨時資料
2、需要多次通路一個開銷昂貴的處理結果
示例:此處是一個簡單查詢,僅展示臨時表的操作
select id,name,UserName
into #temp
from dbo.SystemUsers where Name like '%a%';
select * from dbo.#temp;
drop table #temp;
全局臨時表采用兩個##