简体   繁体   中英

How to use count with CASE condition in a MySQL query?

SELECT
COUNT(
 CASE WHEN ( DATE(igs.start_date) >= DATE('2020-05-01') 
           AND DATE(igs.start_date) <= DATE('2020-05-31') 
      THEN igs.id 
      ELSE 0
 END
) AS totalSessions
FROM
`ignite_session` igs

My requirement is I want session count of a particular month. From above query, I am getting the wrong count. When I checked with the below query it is 0.

 SELECT
      COUNT(id)
 FROM
      ignite_session igs
 WHERE
      DATE(igs.start_date) >= DATE('2020-05-01') 
      AND DATE(igs.start_date) <= DATE('2020-05-31')

The First Query is small part of complex query. I do not want to use date condition in where statement. Please help me with this CASE STATEMENT query. totalSessions should return 0.

You should use a NULL in your else case.

like:

SELECT
COUNT(
    CASE WHEN (DATE(igs.start_date) >= DATE('2020-05-01') 
        AND DATE(igs.start_date) <= DATE('2020-05-31'))
    THEN igs.id 
    ELSE NULL
    END
) AS totalSessions
FROM
`ignite_session` igs

SQL Fiddle

MySQL 5.6 Schema Setup :

CREATE TABLE t1
    (`c1` int)
;
    
INSERT INTO t1
    (`c1`)
VALUES
    (1),
    (2),
    (3),
    (4),
    (5)
;

Query 1 :

select count(case when c1 > 2 then 1 else null end) as nb_count from t1

Results :

| nb_count |
|----------|
|        3 |

Here's an EXAMPLE of what your current query is giving you without COUNT :

SELECT
        CASE WHEN DATE(igs.start_date) >= DATE('2020-05-01') 
        AND DATE(igs.start_date) <= DATE('2020-05- 
        31') THEN igs.id ELSE 0
        END
    AS totalSessions
    FROM
    `ignite_session` igs;

+---------------+
| totalSessions |
+---------------+
| 0             |
| 0             |
| 0             |
| 0             |
+---------------+
*4 row(s) returned.

So with COUNT , it founded rows being returned thats why you get something in your totalSessions even if you didn't any data for that date range. But with a minor change to your query, you can get the correct result. Instead of COUNT , use SUM . Like this example:

SELECT
    SUM(CASE WHEN DATE(igs.start_date) >= DATE('2020-05-01') AND DATE(igs.start_date) <= DATE('2020-05- 
    31') THEN 1 -- change to 1 instead of igs.id
        ELSE 0
    END)
AS totalSessions
FROM
`ignite_session` igs;

Or a much shorter version (similar to Akina's suggestion in the comment):

SELECT SUM(DATE(igs.start_date) >= '2020-06-01' AND DATE(igs.start_date) <= '2020-05-31')
 FROM ignite_session igs;

Here's a demo .

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