如题所示:需要生成交叉表格报表以汇总数据时。 常用到 PIVOT ,例如,假设需要在 AdventureWorks
示例数据库中查询 PurchaseOrderHeader
表以确定由某些特定雇员所下的采购订单数。以下查询提供了此报表(按供应商划分)在透视子句中指定的每个 EmployeeID
号(在本例中为雇员 164、198、223、231 和 233)都有相应的一列 如图所示:
这意味着 EmployeeID
列返回的唯一值自行变成了最终结果集中的字段。
Code
USE AdventureWorks;
GO
SELECT VendorID, [164] as '员工164', [198] as '员工198', [223] as '员工223', [231] as '员工231', [233] as '员工233'
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [164], [198], [223], [231], [233] )
) AS pvt
ORDER BY VendorID
SELECT VendorID,EmployeeID,count(VendorID) as 'count'
FROM Purchasing.PurchaseOrderHeader
where EmployeeID in (164,198,223,231,233)
group by VendorID,EmployeeID
ORDER BY VendorID,EmployeeID
帮助:ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.zh-CHS/udb9/html/24ba54fc-98f7-4d35-8881-b5158aac1d66.htm