我正在使用Microsoft SQL Server 2008.我有一个名为“Tools”的表,其中包含以下列[ID],[QtyOnHand],[SizeUS],[PlantID]。典型的小数据样本可能是这样的:
我想按大小对数据进行分组,并且每个工厂都有一个列总和数量的列,如下所示:
我尝试了以下查询,但这不正确。
SELECT
T.SizeUS
,(
SELECT SUM(T.QtyOnHand)
From Tools T1
WHERE T1.PlantID=1 AND T1.SizeUS=T.SizeUS
) As QtyPlant1
,(
SELECT SUM(T.QtyOnHand)
From Tools T2
WHERE T2.PlantID=2 AND T2.SizeUS=T.SizeUS
) As QtyPlant2
,(
SELECT SUM(T.QtyOnHand)
From Tools T5
WHERE T5.PlantID=5 AND T5.SizeUS=T.SizeUS
) As QtyPlant5
FROM
Tools T
GROUP BY
T.SizeUS;
答案 0 :(得分:3)
试试这个:
SELECT T.SizeUS,
, sum(case when T1.PlantID = 1 then 1 else 0 end) as QtyPlant1
, sum(case when T1.PlantID = 2 then 1 else 0 end) as QtyPlant2
, sum(case when T1.PlantID = 5 then 1 else 0 end) as QtyPlant5
FROM Tools T
Group By T.SizeUS