来自一个表的不同值计数的总和

时间:2013-06-13 03:49:52

标签: mysql database

我遇到选择排序数据的问题。 我解释了我的问题:

表学生:

id  name    degree
1   Adam    11
2   Adam    12
3   Beny    11
4   Beny    13
5   Charly  12
6   Adam    11

我想得到这样的结果:

name    degree 11   degree 12   degree 13
Adam    2           1            0
Beny    1           0            1
Charly  0           1            0

我混淆了获得结果的方式..我尝试使用join,union并且仍然没有得到解决方案。请给我建议解决它。感谢

2 个答案:

答案 0 :(得分:6)

如果你知道degree的数量,可以使用静态查询

来完成
SELECT  Name,
        SUM(CASE WHEN degree = 11 THEN 1 ELSE 0 END) `degree 11`,
        SUM(CASE WHEN degree = 12 THEN 1 ELSE 0 END) `degree 12`,
        SUM(CASE WHEN degree = 13 THEN 1 ELSE 0 END) `degree 13`
FROM    tableName
GROUP   BY Name

输出

╔════════╦═══════════╦═══════════╦═══════════╗
║  NAME  ║ DEGREE 11 ║ DEGREE 12 ║ DEGREE 13 ║
╠════════╬═══════════╬═══════════╬═══════════╣
║ Adam   ║         2 ║         1 ║         0 ║
║ Beny   ║         1 ║         0 ║         1 ║
║ Charly ║         0 ║         1 ║         0 ║
╚════════╩═══════════╩═══════════╩═══════════╝

否则,如果您的学位数未知,则更优选的解决方案是创建动态查询。

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('SUM(CASE WHEN degree = ',
               degree,
               ' THEN 1 ELSE 0 END) AS ',
               CONCAT('`degree ', degree, '`')
               )) INTO @sql
FROM Tablename;

SET @sql = CONCAT('SELECT  Name, ', @sql, ' 
                  FROM    tableName
                  GROUP   BY Name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

答案 1 :(得分:0)

select name, 
       sum(if(degree=11,1,0)) "degree 11",
       sum(if(degree=12,1,0)) "degree 12",
       sum(if(degree=13,1,0)) "degree 13" 
from student
group by name;