I select month and year with range Jan-23 to March 23. The output expected should be as shown below using mysql query or stored procedure.
Jan-23 Present | Jan-23Absent | Feb-23Present | Feb-23Absent | |
---|---|---|---|---|
Class A | 22 | 23 | 10 | 30 |
Class B | 22 | 23 | 10 | 30 |
Class C | 15 | 2 | 12 | 35 |
I tried using the below query:
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
This resulted in:
Present | Absent | |
---|---|---|
Class A | 1 | 2 |
Class B | 3 | 4 |
I need the solution at the very earliest. Thank you.
You should simply be able to add another condition inside your conditional sum, and use the
YEAR()
andMONTH()
functions to check the date:If you want to make the generation of columns dynamic according to the date range, then you can use a recursive CTE to generate the statement:
The CTE at the top just generates a list of all the months between fromDate and toDate, and the SELECT part then uses this list to construct a new SQL statement using these months.
Putting this all together, you could call this from within a stored procedure like this:
You could call this stored procedure like this:
This approach is a bit fiddly - arguably this kind of logic might better be done in your application layer. However, this should give you the result you're looking for.