MySQL:将列值转换为带有总计的标题

标签 mysql header reformat

我有一个 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/

相关文章:

c# - 无法从 C# 应用程序连接远程服务器 mysql 数据库

http - 添加 X-Request-Guid header 是什么意思

c - 为什么编译器在包含标准库中的头文件时不需要传递相应的源文件?

python - 如何使用 Pandas 删除丢失的数据和 0,同时保持数据框相同的形状?

phpmyadmin 显示 utf 8 但站点没有

MySQL:从一个表中选择两次

mysql - 将 Postgresql 表转换为 Mysql 表

rest - 如何在 Apache Benchmark 中传递多个 header

xml - 在 IntelliJ IDEA 中重新格式化混合内容 XML

vim - 在 vim 中重新格式化以获得漂亮的列布局