UNION 運算符:
將兩個或更多查詢的結果組合為單個結果集,該結果集包含聯合查詢中的所有查詢的全部行。這與使用聯接組合兩個表中的列不同。
使用 UNION 組合兩個查詢的結果集的兩個基本規則是:
所有查詢中的列數和列的順序必須相同。
數據類型必須兼容。
這種多結果的查詢組合為單一結果集在實際中應用的非常方便。但在應用中也有有著問題,如下實例可以進一步說明問題。
問題描述:
為了進一步分析與統計企業中關鍵部件的生產進度情況,采用了一個表Key_Item_Cal,其結構如圖一:
通過聯合查詢,將查詢分為三個方面:
1、提出數據的基礎明細,其代碼如下:
SELECT dbo.Key_item.Key_item_name AS Item_Name,
dbo.H_MORVE.QTY_RECVD1 AS Quantity, dbo.Key_item.Style AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item <> 1)
Order by Style asc
其結果為:
2、提出數據的一級匯總明細,其代碼如下:
SELECT dbo.Key_item.Key_item_name AS Item_Name,
SUM(dbo.H_MORVE.QTY_RECVD1) AS Quantity,MAX(dbo.Key_item.Style) AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item <> 1)
GROUP BY dbo.Key_item.Style,dbo.Key_item.Key_item_name
order by Style
其結果如圖如示:
3、提出數據的二級匯總明細,其代碼如下:
SELECT MAX(dbo.Key_item.Key_item_name) as Item_Name,
SUM(dbo.H_MORVE.QTY_RECVD1) as Quantity,
dbo.Key_item.Style as Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
GROUP BY dbo.Key_item.Style
ORDER BY dbo.Key_item.Style asc
其結果如圖所示:
總體的設計就如以上所示,但通過UNION聯接的時候出現了新的問題。通過以下例子,就可以看出UNION與UNION ALL的區別
方案一,其代碼如下:
SELECT dbo.Key_item.Key_item_name AS Item_Name,
dbo.H_MORVE.QTY_RECVD1 AS Quantity, dbo.Key_item.Style AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item <> 1)
UNION (
SELECT dbo.Key_item.Key_item_name AS Item_Name,
SUM(dbo.H_MORVE.QTY_RECVD1) AS Quantity,MAX(dbo.Key_item.Style) AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item <> 1)
GROUP BY dbo.Key_item.Style,dbo.Key_item.Key_item_name
UNION
SELECT MAX(dbo.Key_item.Key_item_name) as Item_Name, SUM(dbo.H_MORVE.QTY_RECVD1) as Quantity,