从同一列中选择每日特定值

时间:2014-12-30 17:06:07

标签: mysql sql database

我正在构建一个反馈工具,我有一个反馈表,其中包含以下结构:

ID  |  Satisfaction  |  Timestamp
--------------------------------------------
 1                0     2014-01-01 00:00:00
 2                5     2014-01-01 00:00:00
 3               10     2014-01-02 00:00:00
 4                5     2014-01-02 00:00:00
 5               10     2014-01-03 00:00:00
 6                0     2014-01-03 00:00:00
 7               10     2014-01-03 00:00:00
 8                5     2014-01-04 00:00:00
 9                5     2014-01-04 00:00:00

如何获得每个"满意度"的每日数量?值?

例如:

Date        |  0's  |  5's  |  10's          
--------------------------------------
2014-01-01  |  1    |  1    |  0
2014-01-02  |  0    |  1    |  1
2014-01-03  |  1    |  0    |  2
2014-01-04  |  0    |  2    |  0

我想象它涉及GROUP BY时间戳,但我不确定如何选择

2 个答案:

答案 0 :(得分:3)

在MySQL中转移此数据的最简单方法:

select date(timestamp),
       sum(satisfaction = 0) as zeroes,
       sum(satisfaction = 5) as fives,
       sum(satisfaction = 10) as tens
from feedback
group by date(timestamp);

答案 1 :(得分:0)

解决!我能够使用sum()和case语句的组合来获取各个值的计数。

SELECT
  DATE(timestamp),
  IFNULL(sum(case when satisfaction = 0 then 1 end), 0) as 'unhappy',
  IFNULL(sum(case when satisfaction = 5 then 1 end), 0) as 'neutral',
  IFNULL(sum(case when satisfaction = 10 then 1 end), 0) as 'happy' 
FROM feedback
GROUP BY DATE(timestamp)