我正在寻找一个解决方案,成为一个漂亮的表,看起来像这样:
ID | A | B | C
-------------------------------
1 | 15 | 4 | 3
2 | 3 | 7 | 1
Run Code Online (Sandbox Code Playgroud)
来源是这样的:
ID | Type
--------------
1 | A
2 | A
1 | C
1 | C
2 | C
1 | B
2 | A
1 | B
Run Code Online (Sandbox Code Playgroud)
现在我要计算每个ID的所有A-Type和所有B-Type.
有一个简单的方法吗?
谢谢
这种类型的数据转换称为数据转换.MySQL没有pivot函数,但您可以使用带有CASE表达式的聚合函数来获取结果:
select id,
count(case when type = 'A' then 1 end) A,
count(case when type = 'B' then 1 end) B,
count(case when type = 'C' then 1 end) C
from yourtable
group by id;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43 次 |
| 最近记录: |