MySQL Count + Grouping for Field值

时间:2012-07-18 07:48:54

标签: mysql sql

我有一张桌子:

Date       | Code

2012-04-01 | 1
2012-04-01 | 0
2012-04-01 | 0
2012-04-01 | 2
2012-04-02 | 4
2012-04-03 | 1
2012-04-03 | 0
2012-04-03 | 0
2012-04-04 | 1
2012-04-04 | 3
2012-04-04 | 4
2012-04-04 | 4
2012-04-04 | 0

代码是从0-5预定义的。

我想要的是一个按规范计算的查询&日期,每个记录为1个日期。 每个预定义的代码都应该在一个单独的字段中计算。

所以,结果应该是:

Date       | Code0 | Code1 | Code2 | Code3 | Code4 | Code5

2012-04-01 |     2 |     1 |     1 |     0 |     0 |     0 
2012-04-02 |     0 |     0 |     0 |     0 |     1 |     0 
2012-04-03 |     2 |     1 |     0 |     0 |     0 |     0 
2012-04-04 |     1 |     1 |     0 |     3 |     4 |     0 

我想以最有效的方式做到这一点,数据大小约为400,000,因此一些基于联合的查询可能会损害数据库。

提前致谢。

2 个答案:

答案 0 :(得分:3)

select `date`, 
       sum(code=0) as code0, 
       sum(code=1) as code1,
       sum(code=2) as code2,
       sum(code=3) as code3, 
       sum(code=4) as code4, 
       sum(code=5) as code5           
from your_table
group by `date`

答案 1 :(得分:1)

SELECT
  `Date`,
  SUM(IF(`Code`=0,1,0)) AS `Code0`,
  SUM(IF(`Code`=1,1,0)) AS `Code1`,
  SUM(IF(`Code`=2,1,0)) AS `Code2`,
  SUM(IF(`Code`=3,1,0)) AS `Code3`,
  SUM(IF(`Code`=4,1,0)) AS `Code4`
FROM
  tablename
GROUP BY `Date`

这将只遍历你的表一次,这是最好的。