如何在过去30天内在sql中显示记录

时间:2014-01-15 02:03:00

标签: mysql sql

表X中的原始数据

+----------+-----+
|Date      |Count|
+----------+-----+
|2014-01-15|44   |
+----------+-----+
|2014-01-01|5    |
+----------+-----+
|2013-12-10|1    |
+----------+-----+

我想要显示的内容如下:

+----------+-----+
|Date      |Count|
+----------+-----+
|2014-01-15|44   |
+----------+-----+
|2014-01-14|0    |
+----------+-----+
|2014-01-13|0    |
+----------+-----+
|2014-01-12|0    |
+----------+-----+
|...       |...  |

* p / s等,直到2013-12-14或2013-12-15

*如何解决问题 - 'curdate'/'NOW'/'subdate'不是公认的内置函数名。

2 个答案:

答案 0 :(得分:2)

在MySQL中,您必须执行以下操作:

select date_sub(date(now()), interval n.n day), coalesce(t.`count`, 0)
from (select 0 as n union all select 1 union all select 2 union all select 3 union all
      . . .
      select 30
     ) n left join
     table t
     on t.date = date_sub(date(now()), interval n.n day);

第一部分是30个数字的手动清单。

答案 1 :(得分:0)

一种选择是创建日期查找表,然后使用outer joindate_sub。此查询应该适合您:

select d.datefield, coalesce(x.count,0) count
from datelookup d
  left join x on d.datefield = x.datefield
where d.datefield > date_sub(curdate(), interval 30 day)
  and d.datefield <= curdate()
order by d.datefield desc