我有2张桌子,主要和单位.
主表:
Todate Unit CategoryID Quantity
1/7/2012 1 S 300
1/7/2012 1 U 350
2/7/2012 2 S 220
3/7/2012 2 S 50
3/7/2012 2 U 330
4/7/2012 1 S 200
4/7/2012 1 U 180
S =销售额,U =升级
单位表:
UnitNum UnitName
1 Measures
2 Performance
我需要得到这个结果:
Todate UnitNum UnitName Sales Upgrades
1/7/2012 1 Measures 300 350
2/7/2012 2 Performance 220
3/7/2012 2 Performance 50 330
4/7/2012 1 Measures 200 180
这意味着我需要创建2列 – 销售和升级,具体取决于CategoryID中的值,我需要它们在同一行.
到目前为止,我有这个
select Todate, Main.Unit, UnitName,
case when CategoryID = 'S' then Quantity end as Sales,
case when CategoryID = 'U' then Quantity end as Upgrades
from Main join Units on Main.UnitNum = Units.UnitNum
group by Todate, Main.Unit, UnitName
它给了我2个新列,但是它们分成两行.
我真的很感激有任何帮助解决这个问题!
谢谢
最佳答案 您只需要围绕case语句进行聚合查询.
select m.todate
, m.unit
, u.unitname
, sum(case when m.categoryid = 'S' then quantity end ) as sales
, sum(case when m.categoryid = 'U' then quantity end ) as upgrages
from main m
join units u
on m.unit = u.unitnum
group by m.todate, m.unit, u.unitname