我有一个 MySQL 表 'dogs' 的结构如下:
AgLevel DogType Total
1 1 10
2 1 29
3 1 30
1 2 20
2 2 14
3 2 28
所以这表示有 10 只 1 型狗,ag 水平为 1,29 只 1 型狗,ag 水平为 2 等。
我想像这样重新格式化它:
DogType Ag1 Ag2 Ag3
1 10 29 30
2 20 14 28
所以在这里我们可以再次看到有 10 只 aglevel 为 1 的 1 型狗。
我该怎么做?
最佳答案
select dogType,
sum(case when agLevel = 1 then total else 0 end) as ag1,
sum(case when agLevel = 2 then total else 0 end) as ag2,
sum(case when agLevel = 3 then total else 0 end) as ag3
from dogs
group by dogType
关于MySQL:将列值转换为带有总计的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31798033/