我如何用mysql获得最近5天的总数?

时间:2012-11-11 11:05:58

标签: mysql sql

我的表格如下:

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

现在,我想计算每个答案A1A2A3的过去5天的总答案。

输出应该是:

answer  count(answer) 
A1      20 
A2      0
A3      34

我如何用MySQL做到这一点?

2 个答案:

答案 0 :(得分:2)

<击> 试试这个:

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

SQL Fiddle Demo

<击>

更新:请改为尝试:

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 fiddle Demo

答案 1 :(得分: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;