2008年10月16日 星期四

Union(多個結果集合併)

/*
Union ---不包含重複(Distinct)
Union All ---全部
1.各結果集欄位數須相同
2.同一欄位型別需相同
*/

Select Convert(char(9),EmployeeID) as 'EmployeeID',LastName,HireDate
from Northwind.dbo.Employees
union
select emp_id,lname,hire_date
From pubs.dbo.employee

--列出產品目錄'1'中庫存量不足或安全存量不足的產品
Select ProductID,ProductName,CategoryID,UnitsInStock,UnitsOnOrder,ReorderLevel
from dbo.Products
where CategoryID=1 and (UnitsInStock<UnitsOnOrder or UnitsInStock<ReorderLevel )
----Union
Select ProductID,ProductName,CategoryID,UnitsInStock,UnitsOnOrder,ReorderLevel
from dbo.Products
where CategoryID=1 and UnitsInStock<UnitsOnOrder
union
Select ProductID,ProductName,CategoryID,UnitsInStock,UnitsOnOrder,ReorderLevel
from dbo.Products
where CategoryID=1 and UnitsInStock<ReorderLevel
---Union All
Select distinct Country
from dbo.Employees
union all ---(可允許重複)
Select distinct Country
from dbo.Customers

沒有留言: