我选择月份和年份,范围为 1 月 23 日到 3 月 23 日。使用 mysql 查询或存储过程的预期输出应如下所示。
1 月 23 日礼物 | 1 月 23 日缺席 | 2 月 23 日现在 | 2 月 23 日缺席 | |
---|---|---|---|---|
A级 | 22 | 23 | 10 | 30 |
B级 | 22 | 23 | 10 | 30 |
C级 | 15 | 2 | 12 | 35 |
我尝试使用以下查询:
SELECT class as 'Class',
sum(if(Attendance='Present',1,0))as 'Present',
sum(if(Attendance='Absent',1,0))as 'Absent'
FROM attendance_data
where date(attendance_date) between '2023-09-01' and '2023-11-01'
group by class
这导致:
现在 | 缺席 | |
---|---|---|
A级 | 1 | 2 |
B级 | 3 | 4 |
我尽早需要解决方案。 谢谢你。
您应该能够在条件和中添加另一个条件,并使用
MONTH()
函数来检查日期:
SELECT class AS 'Class',
SUM(Attendance = 'Present' AND MONTH(attendance_date) = 1) AS 'Jan-23Present',
SUM(Attendance = 'Absent' AND MONTH(attendance_date) = 1) AS 'Jan-23Absent',
SUM(Attendance = 'Present' AND MONTH(attendance_date) = 2) AS 'Feb-23Present',
SUM(Attendance = 'Absent' AND MONTH(attendance_date) = 2) AS 'Feb-23Absent'
FROM attendance_data
WHERE DATE(attendance_date) BETWEEN '2023-01-01' AND '2023-02-28'
GROUP BY class