计算另一个表中存在的值并旋转结果

时间:2016-02-06 23:47:36

标签: mysql sql count pivot

我想从Chat表格中计算值:

ID    REASON_ID    DEPARTMENT_ID    
 1      46           1
 2      46           1
 3      50           1
 4      50           2
 5      100          1 
 6      100          2

那些存在于Reason表中:

ID    REASON_NAME
46    Reason1
50    Reason2
100   Reason3

DEPARTMENT_ID=1,我想要这样的结果:

ID46  ID50  ID100
 2      1     1  

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以尝试以下操作:

chart.group()

SQLFiddle

答案 1 :(得分:1)

动态SQL解决方案更好,但如果您想要其他选项:

SELECT SUM(I46) ID46,
SUM(I50) ID50,
SUM(I100) ID100
FROM
(SELECT 
COUNT(CASE WHEN reason_id = 46 THEN 1 END) I46,
COUNT(CASE WHEN reason_id = 50 THEN 1 END) I50,
COUNT(CASE WHEN reason_id = 100 THEN 1 END) I100
FROM chat
WHERE department_id = 1
GROUP BY reason_id) q1;