我有一个包含SerialNo,StockItemId,Type,WareHouseId,NetCount的表 这是我的查询
SELECT Warehouse.WHWorkOrderDetailsSerials.SerialNo
,Warehouse.WHWorkOrderDetails.StockItemId, Warehouse.WHWorkOrderHeader.Type
,Warehouse.WHWorkOrderHeader.WareHouseId
,CASE
WHEN Warehouse.WHWorkOrderHeader.Type IN ('RS', 'RR', 'RT', 'OB')
THEN '1'
ELSE '-1'
END AS NetCount
FROM Warehouse.WHWorkOrderDetails
INNER JOIN Warehouse.WHWorkOrderDetailsSerials
ON Warehouse.WHWorkOrderDetails.Id = Warehouse.WHWorkOrderDetailsSerials.WorkOrderDetailId
INNER JOIN Warehouse.WHWorkOrderHeader
ON Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId = Warehouse.WHWorkOrderHeader.ID
我需要创建一个数据透视表,其中包含每个WorkHouseId的NetCount总和就像excel中的这个数据透视表一样
有什么想法吗?
答案 0 :(得分:0)
您可以更改查询以执行PIVOT,而无需将其放入Excel中。
SELECT SerialNo, [1], [2], [3], [4], [5]
FROM
(SELECT Warehouse.WHWorkOrderDetailsSerials.SerialNo
,Warehouse.WHWorkOrderDetails.StockItemId, Warehouse.WHWorkOrderHeader.Type
,Warehouse.WHWorkOrderHeader.WareHouseId
,CASE
WHEN Warehouse.WHWorkOrderHeader.Type IN ('RS', 'RR', 'RT', 'OB')
THEN '1'
ELSE '-1'
END AS NetCount
FROM Warehouse.WHWorkOrderDetails
INNER JOIN Warehouse.WHWorkOrderDetailsSerials
ON Warehouse.WHWorkOrderDetails.Id = Warehouse.WHWorkOrderDetailsSerials.WorkOrderDetailId
INNER JOIN Warehouse.WHWorkOrderHeader
ON Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId = Warehouse.WHWorkOrderHeader.ID) AS d PIVOT( SUM(NetCount) FOR WareHouseId IN ([1],[2],[3],[4],[5]) )
您似乎不需要原始查询中的所有字段。我更新了以下查询,仅显示您需要的字段。
SELECT SerialNo, [1], [2], [3], [4], [5]
FROM
(SELECT Warehouse.WHWorkOrderDetailsSerials.SerialNo
,Warehouse.WHWorkOrderHeader.WareHouseId
,CASE
WHEN Warehouse.WHWorkOrderHeader.Type IN ('RS', 'RR', 'RT', 'OB')
THEN '1'
ELSE '-1'
END AS NetCount
FROM Warehouse.WHWorkOrderDetails
INNER JOIN Warehouse.WHWorkOrderDetailsSerials
ON Warehouse.WHWorkOrderDetails.Id = Warehouse.WHWorkOrderDetailsSerials.WorkOrderDetailId
INNER JOIN Warehouse.WHWorkOrderHeader
ON Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId = Warehouse.WHWorkOrderHeader.ID) AS d PIVOT( SUM(NetCount) FOR WareHouseId IN ([1],[2],[3],[4],[5]) )