简体   繁体   中英

Mysql combine count query into single column from multiple columns

I have a table 'Details' as below

| ID | NAME   | PARTS | SERVICE | LOCATION | TIME          |
|----|--------|-------|---------|----------|---------------|
| 1  | John   | 5     | Repair  | A        | 1597893635294 |
| 2  | Smith  | 1     | Install | A        | 1597893635294 |
| 3  | Will   | 1     | Repair  | B        | 1597893635294 |
| 4  | Jade   | 10    | Install | A        | 1597893635294 |
| 5  | George | 2     | Install | B        | 1597893635294 |
| 6  | Ray    | 4     | Repair  | A        | 1597893635294 |

I need the total number of rows sorted based service and location

Select SERVICE,LOCATION,count(*) as TOTAL from Details group by SERVICE,LOCATION order by SERVICE desc;

which gives result as

| SERVICE | LOCATION | TOTAL |
|---------|----------|-------|
| Repair  | A        | 2     |
| Repair  | B        | 1     |
| Install | A        | 2     |
| Install | B        | 1     |

I need result as

| SERVICE | A | B | TOTAL |
|---------|---|---|-------|
| Repair  | 2 | 1 | 3     |
| Install | 2 | 1 | 3     |

You can try the below using conditional aggregation

DEMO

Select SERVICE,
       count(case when location='A' then 1 end) as A,
       count(case when location='B' then 1 end) as B,
       count(*) as TOTAL 
from Details group by SERVICE
order by SERVICE desc

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