2

我有这样的表:

id   answers  date    
12   A1       9-nov  
13   A2       10-nov 
14   A3       7-nov  
...                  

现在我想为每个答案计算过去 5 天的总答案A1, A2, A3.

输出应该是这样的:

answer  count(answer) 
A1      20 
A2      0
A3      34

我怎么能用 MySQL 做到这一点?

4

2 回答 2

2

试试这个:

SELECT answers, COUNT(*)
FROM Table1
WHERE DATEDIFF(NOW(), `date`) >= 5
GROUP BY answers;

SQL 小提琴演示

更新:试试这个:

SELECT t1.answers, IFNULL(COUNT(t2.answers), 0)
FROM table1 t1
LEFT JOIN
(
    SELECT DISTINCT answers FROM table1
) t2 ON  t1.answers = t2.answers AND DATEDIFF(NOW(), t1.`date`) <= 5
GROUP BY t1.answers;

SQL 小提琴演示

于 2012-11-11T11:11:00.117 回答
0

过去 5 天是什么意思?您是指从现在开始的最后 5 天,还是表中存在的最后 5 天?如果您的意思是表中存在的最后 5 天,如果您错过了表中的某些天,则可能是 5 天前,那么您可以使用以下内容:

SELECT
  ans.answers, count(last_tab.id)
FROM
  (select distinct answers from tab) ans
  left join
  (select id, answers
   from tabs
        inner join
        (select distinct date from tab order by date desc limit 5) dt
  on tab.date = dt.date) last_tab
  on ans.answers = last_tab.answers
group by ans.answers;
于 2012-11-11T18:01:41.980 回答