我正在使用以下查询:
SELECT p.bp_pod, COUNT(j.max) as 'COUNT',
SUM (CASE WHEN j.max <= 120 AND j.min <= 80 THEN 1 ELSE 0 END),
SUM (CASE WHEN j.max > 120 AND j.max < 140 OR j.min > 80 AND j.min < 90 THEN 1 ELSE 0 END),
SUM (CASE WHEN j.max >= 140 OR j.min >= 90 THEN 1 ELSE 0 END)
FROM (SELECT 0 as bp_pod UNION ALL
SELECT 1 as bp_pod UNION ALL
SELECT 2 as bp_pod )
p LEFT JOIN
tb_journal j
ON p.bp_pod = j.bp_pod
GROUP BY p.bp_pod LIMIT 0, 90;
但是此查询根据bp_pod
对记录进行分组,这些记录只能包含三个值:0, 1, 2
。
以下是我正在使用的table
CREATE TABLE "table" ( `bp_pod` NUMERIC, `max` NUMERIC, `min` NUMERIC )
以下是我正在使用的一些值:
INSERT INTO table VALUES('21', '134', '78');
INSERT INTO table VALUES('13', '126', '88');
INSERT INTO table VALUES('6', '97', '54');
现在我更改了应用程序并且它可以有多个值,因此我需要使用范围实现GROUP BY,例如:
bp_pod > 5 AND bp_pod < 12
bp_pod >= 12 AND bp_pod < 21
bp_pod >= 21 AND bp_pod < 24
但在索引pod
0,1,2。
预期结果如下:
pod COUNT range_1 range_2 range_3
0 0 1 0 0
1 0 0 1 0
2 0 0 0 1
有任何线索吗? 谢谢。
答案 0 :(得分:1)
由于left join
,您需要小心。我认为这样做你想要的:
SELECT p.pod,
COUNT(j.bp_max) as 'COUNT',
SUM(CASE WHEN j.max <= 120 AND j.min <= 80 THEN 1 ELSE 0 END),
SUM(CASE WHEN j.max > 120 AND j.max < 140 OR j.min > 80 AND j.min < 90 THEN 1 ELSE 0 END),
SUM(CASE WHEN j.max >= 140 OR j.min >= 90 THEN 1 ELSE 0 END)
FROM (SELECT 0 as bp_pod, 5 as minb, 12 as maxb UNION ALL
SELECT 1 as bp_pod, 12, 21 UNION ALL
SELECT 2 as bp_pod, 21, 24
) p LEFT JOIN
tb_journal j
ON j.bp_pod >= p.minb AND j.bp_pod < p.maxb
GROUP BY p.bp_pod;