如果我有下表:
Cust Prod Qty
===== ==== ===
Bob Apple 3
Bob Orange 2
Bob Banana 4
Rob Apple 2
Rob Orange 1
Bob Apple 2
如何以表格数据作为列名获得以下结果:
Prod Bob Rob
====== === ===
Apple 5 2
Orange 2 1
Banana 4 null
答案 0 :(得分:4)
您可以在MSSQL中使用PIVOT或以下方式:
SELECT
PROD,
SUM(CASE WHEN Cust='Bob' THEN Qty ELSE 0 END) as Bob,
SUM(CASE WHEN Cust='Rob' THEN Qty ELSE 0 END) as Rob
FROM T
GROUP BY PROD
答案 1 :(得分:2)
SELECT * from t
pivot
(
sum(Qty)
for [Cust] in ([Bob],[Rob])
)as p;
GROUP BY PROD