我有观察表赞
id ignition mileage`**
1 true 10
2 true 30
3 true 10
4 false 05
5 false 05
6 true 10
7 true 10
8 false 20
9 false 20
10 false 20
我想通过将点火true
和false
值分组来计算里程总和。像
ignition total_mileage
true 50
false 10
true 20
false 60
如何使用分组获得输出
答案 0 :(得分:1)
纯粹主义者可能会指出这种方法存在一些缺陷,但我正在努力保持简洁......
E.g:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,ignition TINYINT NOT NULL
,mileage INT NOT NULL
);
INSERT INTO my_table VALUES
( 1,true,10),
( 2,true ,30),
( 3,true ,10),
( 4,false,05),
( 5,false,05),
( 6,true ,10),
( 7,true ,10),
( 8,false,20),
( 9,false,20),
(10,false,20);
SELECT ignition
, SUM(mileage) total
FROM
( SELECT x.*
, CASE WHEN ignition = @prev THEN @i:=@i ELSE @i:=@i+1 END i
, @prev:=ignition FROM my_table x
,(SELECT @prev:=null,@i:=0) vars
ORDER
BY id
) n
GROUP
BY i;
+----------+-------+
| ignition | total |
+----------+-------+
| 1 | 50 |
| 0 | 10 |
| 1 | 20 |
| 0 | 60 |
+----------+-------+