我希望将下面table1的数据分组显示在表2中。我可以按列分组,但我期望的输出是子分组!
Logic: assetScore => >=0 - <=25 -> LOW, > 25 - <= 60 -> MEDIUM' and > 60 -> HIGH
status => 1 -> Backlog, 2 -> WIP and 3 -> closed
Table-1:
+----+------------+--------+
| id | assetScore | status |
+----+------------+--------+
| 1 | 10 | 1 |
| 2 | 50 | 1 |
| 3 | 32 | 3 |
| 4 | 22 | 1 |
| 5 | 12 | 2 |
| 6 | 14 | 2 |
| 7 | 18 | 3 |
| 8 | 88 | 1 |
| 9 | 65 | 3 |
| 10 | 24 | 3 |
| 11 | 44 | 2 |
| 12 | 66 | 1 |
| 13 | 22 | 3 |
| 14 | 31 | 1 |
| 15 | 36.5 | 3 |
| 16 | 77 | 2 |
+----+------------+--------+
Expected Result:
+--------+---------+-----+--------+
| | Backlog | WIP | Closed |
+--------+---------+-----+--------+
| LOW | 2 | 2 | 3 |
| MEDIUM | 2 | 1 | 2 |
| HIGH | 2 | 1 | 1 |
+--------+---------+-----+--------+
到目前为止,我有以下SQL(仅按资产分数或状态分组):
SELECT
t.RANGE, COUNT(*)
FROM
(SELECT
CASE
WHEN assetScore BETWEEN 0 AND 25 THEN 'LOW'
WHEN assetScore BETWEEN 26 AND 60 THEN 'MEDIUM'
ELSE 'HIGH'
END AS 'RANGE'
FROM device) t
GROUP BY t.RANGE;
答案 0 :(得分:2)
使用case
表达式对范围进行分类并对其使用条件聚合。
SELECT CASE WHEN assetScore BETWEEN 0 AND 25 THEN 'LOW'
WHEN assetScore BETWEEN 26 AND 60 THEN 'MEDIUM'
ELSE 'HIGH'
END AS `RANGE`,
SUM(`status`=1) as backlog,
SUM(`status`=2) as wip,
SUM(`status`=3) as closed
FROM device
GROUP BY CASE WHEN assetScore BETWEEN 0 AND 25 THEN 'LOW'
WHEN assetScore BETWEEN 26 AND 60 THEN 'MEDIUM'
ELSE 'HIGH' END
答案 1 :(得分:2)
您可以简单地为状态添加3个案例并汇总相关值
SELECT
t.RANGE, sum(t.Backlog), sum(t.WIP), sum(t.Closed)
FROM
(SELECT
CASE
WHEN assetScore BETWEEN 0 AND 25 THEN 'LOW'
WHEN assetScore BETWEEN 26 AND 60 THEN 'MEDIUM'
ELSE 'HIGH'
END AS 'RANGE',
CASE when status = 1 then 1 else 0 end as Backlog,
CASE when status = 2 then 1 else 0 end as WIP,
CASE when status = 3 then 1 else 0 end as Closed,
FROM device) t
GROUP BY t.RANGE;