我正在尝试使用SQL从数据库导入一些数据到Excel。
我在以下列中获取数据:
项目#位置数量
但我想以下列格式导入它:
项目#数量@位置1数量@位置2数量@位置3
选择Distinct item#,
情况当location =“location1”那么数量结束时作为QTY @ Location1,
例如,当location =“location2”那么数量结束为QTY @ Location2,
情况当location =“location3”那么数量结束时作为QTY @ Location3
来自table1
然而,这会返回3条记录。有没有办法将这些记录合并为一行?
答案 0 :(得分:0)
您想要进行汇总:
Select item#,
MAX(CASE WHEN location="location1" THEN qty END) AS QTY@Location1,
MAX(CASE WHEN location="location1" THEN qty END) AS QTY@Location1,
MAX(CASE WHEN location="location1" THEN qty END) AS QTY@Location1
From table1
Group By item#;
答案 1 :(得分:0)
是的,我认为聚合行会起作用
Select item#,
Sum(CASE WHEN location="location1" THEN qty else 0 END) AS QTY@Location1,
Sum(CASE WHEN location="location1" THEN qty else 0 END) AS QTY@Location1,
Sum(CASE WHEN location="location1" THEN qty else 0 END) AS QTY@Location1
From table1
group by
item#
答案 2 :(得分:0)
假设'location1''location2'和'location3'是常数,你可以这样做:
SELECT isnull(isnull(loc1.Item, loc2.Item), loc3.Item) as Item,
loc1.Qty as QTY@Location1, loc2.Qty as QTY@Location2, loc3.Qty as QTY@Location3
FROM
(select Item, Qty from table1 where Location = 'location1') as loc1
FULL JOIN
(select Item, Qty from table1 where Location = 'location2') as loc2 ON loc1.Item = loc2.Item
FULL JOIN
(select Item, Qty from table1 where Location = 'location3') as loc3 ON isnull(loc1.Item, loc2.Item) = loc3.Item
答案 3 :(得分:0)
如果您的DBMS支持,PIVOT
将非常巧妙地为您完成此操作。 [这是]关于这个问题的SO问题。