[英]SQL Server - Rows into Columns (Grouped)
我嘗試使用PIVOT將我的一些行合並為列,但事實是,我必須將它們分組,但我不知道該怎么做。
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
不知道這是否能回答您的問題,但是我發現您在group by子句中包含了tipo
,這將導致記錄被拆分,例如“ Mann Co.Supply Crate Key”可以具有0或1的tipo
。根據您的信息。 這將按0 Mann Co. Supply Crate Key
和第二組1 Mann Co. Supply Crate Key
分組。
編輯:查看您的查詢您可能想要這樣的事情:
select
it.itemname as item,
sum(case when resi.tipo = 0 then resi.quantity else 1 end) as qty_0,
sum(case when resi.tipo = 1 then resi.quantity else 0 end) as qty_1
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.itemname
order by tipo, it.id
請記住,不知道表結構會有點困難:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.