0

我有一张桌子:

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,因此一些基于联合的查询可能会损害数据库。

提前致谢。

4

2 回答 2

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`
于 2012-07-18T07:53:24.960 回答
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`

这只会遍历您的表一次,这已经足够好了。

于 2012-07-18T07:53:03.200 回答