简体   繁体   中英

Group rows in multiple columns and count

I have a table with these data :

SELECT typeId, status FROM geo WHERE userId = 1 LIMIT 5;
+--------+--------+
| typeId | status |
+--------+--------+
|      2 | 2      |
|      2 | 5      |
|      8 | 2      |
|      3 | 3      |
|      2 | 5      |
+--------+--------+

And I'd like to count the number of different status per typeID. Here the expected result:

status 2 = active
status 3 = disabled
status 5 = archived

+--------+--------+----------+----------+
| typeId | active | disabled | archived |
+--------+--------+----------+----------+
|      2 | 1      | 0        | 2        |
|      8 | 1      | 0        | 0        |
|      3 | 0      | 1        | 0        |
+--------+--------+----------+----------+

0 can be is NULL, not a problem

I tried with a query like that : "SELECT typeId, CASE WHEN status = 2 THEN status END AS active, CASE WHEN status = 3 THEN status END AS disabled, CASE WHEN status = 5 THEN status END AS archived FROM geo WHERE userId = 1 group by typeId" but of course it's not the expected result.. I got the status, not the count and I don't know how to count them.

Thanks for your help!

You need aggreaation functions:

SELECT typeId, SUM( status = 2 ) AS active, SUM( status = 3 ) AS disabled, SUM( status = 5 ) AS archived
FROM geo
WHERE userId = 1 
GROUP BY typeId;

Note that this uses a convenient MySQL shortcut that sums boolean values "as if" they were integers, with 1 for true and 0 for false.

How about trying this way (for T-SQL):

SELECT typeId,
       SUM(CASE status WHEN '2' THEN 1 ELSE 0 END) AS 'active',
       SUM(CASE status WHEN '3' THEN 1 ELSE 0 END) AS 'disabled',
       SUM(CASE status WHEN '5' THEN 1 ELSE 0 END) AS 'archived'
FROM geo
WHERE userId = 1
GROUP BY typeID

You can use the case expression with count function:

SELECT typeId,
       COUNT(CASE status WHEN '2' THEN 1 END) AS 'active',
       COUNT(CASE status WHEN '3' THEN 1  END) AS 'disabled',
       COUNT(CASE status WHEN '5' THEN 1  END) AS 'archived'
FROM Table1
GROUP BY typeID;

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