1)union內部的select語句必須擁有相同的列,列也必須有類似的數字類型。同時,每條select語句中列的順序相同。spa
union語法(結果集無重複)code
select x from table1 union select y from table2
union all語法(結果集有重複)blog
select x from table1 union all select y from table2
公共表表達式,能夠認爲是在單個 SELECT、INSERT、UPDATE、DELETE 或 CREATE ⅥEW 語句的執行範圍內定義的臨時結果集遞歸
CTE可用於:ci
1).建立遞歸查詢it
2).在同一語句中屢次生成的表io
把test表中salary最大的id記錄保存在test_CTE中,再調用table
with test_CTE(id,salary) as ( select id,max(salary) from test group by id ) select * from test_cte
查詢ItemId=2及子節點,也就是管理費用和其下屬全部節點的信息ast
Declare @i int select @i=2; with Co_ItemNameSet_CTE(ItemId,ParentItemId,ItemName,[Level]) AS ( select ItemId, ParentItemId,ItemName,1 AS [Level] from Co_ItemNameSet where ItemId=@i union all select c.ItemId,c.ParentItemId,c.ItemName,[Level]+1 from Co_ItemNameSet c inner join Co_ItemNameSet_CTE ct on c.ParentItemId=ct.ItemId ) select * from Co_ItemNameSet_CTE
結果:class
--不用partition by select name,Gender,FenShu, row_number()over(order by FenShu desc) as num from dbo.PeopleInfo --使用partition by select name,Gender,FenShu, row_number()over(partition by Gender order by FenShu desc) as num from dbo.PeopleInfo ; --查找出不一樣性別中分數最高的學生 with temp as ( select name,Gender,FenShu, row_number()over(partition by Gender order by FenShu desc) as num from dbo.PeopleInfo ) select * from temp where num=1
從兩個或更多表中獲取結果,就要執行Join
Inner Join
select P.LastName,P.FirstName, O.OrderNo from dbo.Persons as P inner join dbo.mOrder as O on P.Id= O.Id_P order by P.LastName
結果:
left Join
select c.customerid as 消費者,COUNT(O.[orderid]) as 訂單數 from [SQLDemo].[dbo].[Customers] as C left join [SQLDemo].[dbo]. [Orders] as O on C.customerid=O.customerid where C.city='Madrid' group by C.customerid having COUNT(O.orderid)<3 order by 訂單數
/****** SQL 通配符 ******/ select * from Persons where City like '[ALN]%'