我需要显示用户的出勤年份和月份。这是一个样本 看起来如何-非常基本:
Conversation_message::Sender()->first();
从单个表中检索数据,我尝试了以下查询 为此:
Year - Jan - Feb
2018 - 26 - 20
2019 - 20 - 22
很遗憾,这不会返回预期的数据,而是显示年度 用户每月的出勤情况如下:
SELECT EXTRACT(YEAR FROM M.DATE) "YEAR",
COUNT(CASE WHEN EXTRACT(MONTH FROM M.DATE) = '1' THEN M.Id ELSE '-' END) "Jan",
COUNT(CASE WHEN EXTRACT(MONTH FROM M.DATE) = '2' THEN M.Id ELSE '-' END) "Feb"
FROM TABLE m
WHERE M.STATUS = 'P' AND M.Id = '12345678'
GROUP BY EXTRACT(YEAR FROM M.DATE) ORDER BY EXTRACT(YEAR FROM M.DATE);
我在这里错过了什么吗?任何想法将不胜感激。
答案 0 :(得分:1)
试试这个-
SELECT EXTRACT(YEAR FROM M.DATE) "YEAR",
COUNT(CASE WHEN EXTRACT(MONTH FROM M.DATE) = '1' THEN M.Id ELSE NULL END) "Jan",
COUNT(CASE WHEN EXTRACT(MONTH FROM M.DATE) = '2' THEN M.Id ELSE NULL END) "Feb"
FROM TABLE m
WHERE M.STATUS = 'P' AND M.Id = '12345678'
GROUP BY EXTRACT(YEAR FROM M.DATE) ORDER BY EXTRACT(YEAR FROM M.DATE);
OR-
SELECT EXTRACT(YEAR FROM M.DATE) "YEAR",
SUM(CASE WHEN EXTRACT(MONTH FROM M.DATE) = '1' THEN 1 ELSE 0 END) "Jan",
SUM(CASE WHEN EXTRACT(MONTH FROM M.DATE) = '2' THEN 1 ELSE 0 END) "Feb"
FROM TABLE m
WHERE M.STATUS = 'P' AND M.Id = '12345678'
GROUP BY EXTRACT(YEAR FROM M.DATE) ORDER BY EXTRACT(YEAR FROM M.DATE);
答案 1 :(得分:0)
我更喜欢使用SUM()
。但更重要的是,您的代码是混合类型。 EXTRACT()
返回一个数字,因此比较应该是一个数字。我建议:
SELECT EXTRACT(YEAR FROM M.DATE) as "YEAR",
SUM(CASE WHEN EXTRACT(MONTH FROM M.DATE) = 1 THEN 1 ELSE 0 END) as "Jan",
SUM(CASE WHEN EXTRACT(MONTH FROM M.DATE) = 2 THEN 1 ELSE 0 END) as "Feb"
FROM TABLE m
WHERE M.STATUS = 'P' AND
M.Id = 12345678 -- I am guessing that `id` is also a number
GROUP BY EXTRACT(YEAR FROM M.DATE)
ORDER BY EXTRACT(YEAR FROM M.DATE);
您应该小心混合类型。转换可能会妨碍优化器找到最佳查询计划的能力。