MySQL - 根据另一列计算一列中的不同值

时间:2017-09-19 06:58:53

标签: mysql sql pivot

我有包含所有数据的表资源, 我想得到上表中给出的结果.. 请帮帮我

Dept Grade
A    E3  
B    M2  
D    E3  
C    M1  
A    E3  
D    E4  
A    E3    

我使用下面的代码,但我无法得到实际的解决方案

SELECT DISTINCT Department,COUNT(DISTINCT GRADE) as Grades FROM reslookup GROUP BY Department;

about查询的执行结果

Dept Grade
A    3
B    1
C    1
D    2

但是,我希望得到如下所示的结果

Dept E3  E4  M1  M2
A    5   0   2   1
B    4   2   3   0
C    8   9   2   1
D    5   0   2   6

2 个答案:

答案 0 :(得分:3)

您要做的是将 pivot 计数行放入不同的列中,这可以通过以下方式完成:

SELECT Dept,
  SUM(CASE WHEN Grade = 'E3' THEN 1 ELSE 0 END) AS E3, 
  SUM(CASE WHEN Grade = 'E4' THEN 1 ELSE 0 END) AS E4,
  SUM(CASE WHEN Grade = 'M1' THEN 1 ELSE 0 END) AS M1,
  SUM(CASE WHEN Grade = 'M2' THEN 1 ELSE 0 END) AS M2
FROM reslookup 
GROUP BY Dept;

demo

答案 1 :(得分:0)

您也可以使用以下代码提供相同的解决方案

SELECT Dept,
      SUM(Grade = 'E3') AS E3, 
      SUM(Grade = 'E4') AS E4,
      SUM(Grade = 'M1') AS M1,
      SUM(Grade = 'M2') AS M2
    FROM reslookup 
    GROUP BY Dept;