Skip to content
Advertisement

Can I get two count results in a query?

I am using MariaDB. I want to have two count results in a query.

The first query is:

SELECT 
    license_key, 
    COUNT( * ) AS expired
FROM license_product
WHERE expire_at > NOW()
GROUP BY license_key;

Next is:

SELECT 
    license_key, 
    COUNT( * ) AS total
FROM license_product
GROUP BY license_key;

What I want to get is:

+---------------------+---------+---------+
| license_key         | expired |   total |
+---------------------+---------+---------+
| 0DSX-1DXW-ONYK-3QJS |       5 |      10 |
| 1IBR-GSZ4-AHPK-898F |       4 |       8 |
| 4BDD-YQBD-5QGG-XS70 |       2 |       2 |
| 5CJF-O3LY-WSA8-ZKWK |       3 |       5 |
+---------------------+---------+---------+

How can I combine them?

Advertisement

Answer

The usual way is to make a Case..When statement that is one or zero for the desired condition and then SUM it, not COUNT it.

Select license_key,
    sum(Case When expire_at > NOW() Then 1 Else 0 End) as expired,
    COUNT( * ) AS total
FROM license_product
GROUP BY license_key
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement