0
我试图使用PIVOT将我的一些行组合到列中,但事情是,我必须将它们分组,并且我无法弄清楚我该怎么做它。SQL Server - 行分栏(分组)
SQL查询:
select res.tipo,
it.itemname as item,
sum(resi.quantity) as qt
from Reserve as res inner join
ReserveItems as resi on res.id_reserve = resi.id_reserve inner join
Items as it on resi.defindex = it.defindex
where res.situacao = 3
group by res.tipo, it.id, it.itemname
order by tipo, it.id
结果:
tipo item qt ------ ---------------------------------------------------------------------------------------------------- ----------- 0 Mann Co. Supply Crate Key 6 0 Tour of Duty Ticket 10 0 Reinforced Robot Emotion Detector 5 0 Reinforced Robot Bomb Stabilizer 1 0 Battle-Worn Robot Taunt Processor 3 0 Battle-Worn Robot KB-808 22 0 Battle-Worn Robot Money Furnace 19 1 Mann Co. Supply Crate Key 41 1 Tour of Duty Ticket 31 1 Pristine Robot Currency Digestor 1 1 Pristine Robot Brainstorm Bulb 2 1 Reinforced Robot Emotion Detector 32 1 Reinforced Robot Humor Supression Pump 45 1 Reinforced Robot Bomb Stabilizer 39 1 Battle-Worn Robot Taunt Processor 69 1 Battle-Worn Robot KB-808 78 1 Battle-Worn Robot Money Furnace 109
期望的结果:
item qt_1 qt_0 ------------------------------------------ ---------- -------- Mann Co. Supply Crate Key 41 6 Tour of Duty Ticket 27 6 Pristine Robot Currency Digestor 1 0 Pristine Robot Brainstorm Bulb 2 0 Reinforced Robot Emotion Detector 32 5 Reinforced Robot Humor Supression Pump 45 0 Reinforced Robot Bomb Stabilizer 39 1 Battle-Worn Robot Taunt Processor 89 3 Battle-Worn Robot KB-808 92 16 Battle-Worn Robot Money Furnace 109 19
是否有可能在一个简单的方法来做到这一点? (不使用#temp,并插入/更新值)。使用旋转将是最适合我=)
编辑:
该解决方案是基于JanR答案。再次感谢,男士!
select it.itemname as item,
sum(case when res.tipo = 0 then resi.quantity else 0 end) as qt_compra,
sum(case when res.tipo = 1 then resi.quantity else 0 end) as qt_venda
from Reserve as res inner join
ReserveItems as resi on res.id_reserve = resi.id_reserve inner join
Items as it on resi.defindex = it.defindex
where res.situacao = 3
group by it.id, it.itemname
order by it.id
表结构没有#TEMP表?好的,@temp变量或派生表,甚至CTE在做PIVOT之前做分组。 –