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之前做分組。 –