需要在sum操作中使用excel中的数据透视表进行查询

时间:2017-09-26 18:03:43

标签: sql sql-server tsql qtsql

我有一个包含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

Figure 1 我需要创建一个数据透视表,其中包含每个WorkHouseId的NetCount总和就像excel中的这个数据透视表一样 Figure 2

有什么想法吗?

1 个答案:

答案 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]) )