sql查询按类型计算多行

时间:2013-03-17 01:47:19

标签: mysql sql database

也许是一个非平凡的查询,我正在使用这个表http://sqlfiddle.com/#!2/d0423并尝试使用mysql 5.6输出下表

[type][type_cnt][f_cnt_type0][f_cnt_type1][f_cnt_type2][time_00][time_00-15][time_15-30]
10        2         1             1           0           1          1          0
20        3         1             1           1           1          2          0
30        3         2             1           0           0          1          1

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

CREATE TABLE bugs (
     type varchar(2),
     flag varchar(1), 
     mins varchar(2)
 );

INSERT INTO bugs(type, flag, mins) values
('10','0','0'),
('10','1','5'),
('20','0','0'),
('20','1','5'),
('20','2','10'),
('30','0','10'),
('30','0','20'),
('30','1','40');


select 
  type, 
  count(type) as type_cnt,
  SUM(CASE WHEN flag='0' THEN 1 ELSE 0 END) as f_cnt_type0,
  SUM(CASE WHEN flag='1' THEN 1 ELSE 0 END) as f_cnt_type1,
  SUM(CASE WHEN flag='2' THEN 1 ELSE 0 END) as f_cnt_type2,
  SUM(CASE WHEN CAST(mins AS UNSIGNED) = 0 THEN 1 ELSE 0 END) as time_00,
  SUM(CASE WHEN CAST(mins AS UNSIGNED) > 0 and CAST(mins AS UNSIGNED) <= 15 THEN 1 ELSE 0 END) as time_00_15,
  SUM(CASE WHEN CAST(mins AS UNSIGNED) > 15 and CAST(mins AS UNSIGNED) <= 30 THEN 1 ELSE 0 END) as time_15_30       
from bugs
group by type

SQL:sqlfiddle