简体   繁体   中英

PHP mysql query group by two column and count

I have a table as below.

-----------------------------------
| subject | ID | date   | status  |
+---------+----+--------+---------+
| S1997   |153 |25/4/19 | Late    |
| S1997   |154 |25/4/19 | Present |
| S1997   |153 |26/4/19 | Present |
| S1997   |154 |26/4/19 | Present |
| S1999   |153 |27/4/19 | Present |
| S1999   |154 |27/4/19 | Late    |
-----------------------------------

How do I write a query to get the result as below

 ----------------------------------------
 | subject | ID | total attendance| late|
 +---------+----+-----------------+------
 | S1997   |153 |        2        |  1  |
 | S1997   |154 |        2        |  0  |
 | S1999   |153 |        1        |  0  |
 | S1999   |154 |        1        |  1  |
 ----------------------------------------

I tried using GROUP BY but I could not get the table as I want above.

use group by and aggregation

select subject, id, count(date) as totalattendance, 
       count(case when status='late' then 1 end) as late
from tablename
group by subject, id

A slight variation of the answer given by @fa06:

SELECT
    subject,
    id,
    COUNT(*) AS `total attendance`,
    SUM(status = 'late') AS late
FROM yourTable
GROUP BY
    subject,
    id;

We can take advantage of MySQL's conditional SUM function to avoid using a CASE expression.

You can get the desired result by using COUNT , SUM and GROUP BY

SELECT subject,ID,COUNT(*) AS `total attendance`,SUM(IF(status = 'Late', 1, 0)) 
AS late 
FROM `tablename` 
GROUP BY subject,ID

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