如何对多列数据进行分组

huangapple go评论50阅读模式
英文:

How to group multiple columns data

问题

以下是翻译好的部分:

在下表中,我想将产品名称分组,然后将数量总和放在每个型号名称下。

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 Product

期望的输出

Product M1 M2 M3
Banana 2.0
Apple 0.5
Pawpaw 1.5
Orange 0.5 2.0
英文:

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

tblStore

ID Product Model Qty
1 Banana M1 1.00
2 Apple M3 0.50
3 Pawpaw M3 1.50
4 Orange M2 2.00
5 Banana M1 1.00
6 Orange M1 0.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

Product M1 M2 M3
Banana 2.0
Apple 0.5
Pawpaw 1.5
Orange 0.5 2.0

答案1

得分: 0

你的列引用有点颠倒,你想要的是以下内容:

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;
英文:

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;

huangapple
  • 本文由 发表于 2023年5月25日 03:18:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定