SQL使用“是”或“否”获取两列

时间:2017-12-14 18:45:09

标签: php mysql sql

我有一个查询,我选择所有的sendIntakes并按照主管身份和年份对它们进行分组。

sendResponse列是否已响应,0为否,1为是。

                     SELECT officiantId, COUNT(*) as ct, sendResponse,
                     Year(created_at) as yr
                     FROM sendIntakes
                     Where sendResponse is not null                   

                     GROUP BY officiantId, sendResponse, YEAR(created_at)
                     ORDER BY officiantId, yr
                     DESC;

虽然如果计数为0/1

,它会创建一个新行
officiant id - 404 | ct - 2 | sendResponse 1 | yr 2017
officiant id - 404 | ct - 1 | sendResponse 0 | yr 2017
officiant id - 547 | ct - 1 | sendResponse 1 | yr 2017

有没有办法摆脱sendResponse,并将其作为

officiant id - 404 | ct - 2 | Yes - 1 | No - 1 | yr 2017

1 个答案:

答案 0 :(得分:0)

您可以通过删除GROUP BY

中的sendResponse来计算每次出现的是和否(1或0)
SELECT officiantId, COUNT(*) as ct, 
SUM(CASE WHEN sendResponse = 1 THEN 1 ELSE 0 END) as Yes,
SUM(CASE WHEN sendResponse = 0 THEN 1 ELSE 0 END) as No,
Year(created_at) as yr
FROM sendIntakes
Where sendResponse is not null                   

GROUP BY officiantId, YEAR(created_at)
ORDER BY officiantId, yr
DESC;