mysql 範圍統計,而且行轉列

-- 建立數據庫
create table score(id int not null auto_increment,score int not null,primary key (id))engine=myisam;
-- 插入數據
insert into score(`score`) values(100),(200),(200),(100),(300),(400),(500),(300),(200),(400),(500),(200),(500),(300);

-- 範圍查詢,而且行轉列
select 
	sum(if(a.score_class = 1,1,0)) as w_1,
	sum(if(a.score_class =2 ,1,0)) as w_2,
    sum(if(a.score_class = 3,1,0)) as w_3,
	sum(if(a.score_class =4 ,1,0)) as w_4,
    sum(if(a.score_class = 5,1,0)) as w_5

  from (select id,score,
(case 
when  score >=100 and score <=200 then 1
when  score >200  and score <=300 then 2
when  score >300  and score <=400 then 3
when  score >400  and score <=500 then 4
else 5
end) as  score_class from score) as a;

-- output
+------+------+------+------+------+
| w_1  | w_2  | w_3  | w_4  | w_5  |
+------+------+------+------+------+
|    7 |    3 |    2 |    3 |    0 |
+------+------+------+------+------+
1 row in set (0.00 sec)
-- explain 
+----+-------------+------------+------+---------------+------+---------+------+------+-------+
| id | select_type | table      | type | possible_keys | key  | key_len | ref  | rows | Extra |
+----+-------------+------------+------+---------------+------+---------+------+------+-------+
|  1 | PRIMARY     | <derived2> | ALL  | NULL          | NULL | NULL    | NULL |   15 | NULL  |
|  2 | DERIVED     | score      | ALL  | NULL          | NULL | NULL    | NULL |   15 | NULL  |
+----+-------------+------------+------+---------------+------+---------+------+------+-------+

-- index

mysql> show index from score;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| score |          0 | PRIMARY  |            1 | id          | A         |          15 |     NULL | NULL   |      | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec)
相關文章
相關標籤/搜索