SQL Server How to group multiple columns data

mhd8tkvw  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(125)

In the below table I want to group the product name then sum the quantity to be under each Model name.

tblStore

IDProductModelQty
1BananaM11.00
2AppleM30.50
3PawpawM31.50
4OrangeM22.00
5BananaM11.00
6OrangeM10.50
Select Product, 
    Sum(Case When tblStore.Quantity  = 'M1' Then 1 Else 0 End) As M1,
    Sum(Case When tblStore.Quantity  = 'M2' Then 1 Else 0 End) As M2,
    Sum(Case When tblStore.Quantity  = 'M3' Then 1 Else 0 End) As M3
From tblStore
Group by Name

Expected output

ProductM1M2M3
Banana2.0
Apple0.5
Pawpaw1.5
Orange0.52.0
jdzmm42g

jdzmm42g1#

You have your column references a bit backwards, you are after the following:

select Product, 
 Sum(case when Model = 'M1' then Qty else 0 end) M1,
 Sum(case when Model = 'M2' then Qty else 0 end) M2,
 Sum(case when Model = 'M3' then Qty else 0 end) M3
from tblStore 
group by Product;

相关问题