简体   繁体   中英

How to get both present and absent students for a year

I need to get the total no. present and absent students in a year from a table attendance: Here is my query:

SELECT if( status = 'P',count(level_id), 0) AS present, 
       if(status='A',count(student_id), 0) AS Absent 
        FROM attendance WHERE level_id = 'L1' AND date LIKE '2016%'

But this returns the total no. of students to either present or absent section.

The problem is that you misunderstood what COUNT(...) does in the query. If you really want to count based on being absent or present, then you can use SUM(...) with a conditional step inside.

SELECT
    SUM(if(status = 'P', 1, 0)) AS Present
    SUM(if(status = 'A', 1, 0)) AS Absent
FROM
    attendance
WHERE
    level_id = 'L1' AND date LIKE '2016%'

Return 1 if you need to count th element:

 SELECT SUM(if( status = 'P',1, 0)) AS present, SUM(if(status='A',1, 0)) AS Absent
 FROM attendance WHERE level_id = 'L1' AND date LIKE '2016%'

Try group by clause like:

SELECT 
 status, 
 count(student_id) as attendance 
FROM attendance 
WHERE level_id = 'L1' 
  AND date LIKE '2016%' 
GROUP BY status;

It will give you the count for each status available in table

这将起作用:

SELECT DISTINCT(student_name), SUM(status = 'P') AS present, SUM(status='A') AS Absent FROM attendance GROUP BY student_name where date LIKE '2016%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM