我有一个具有以下结构的数据库表
id | dateCreated | numOfUsers
典型行为 1, '2011-10-13 12:00:00', 4
我的行包含过去 4 个月的数据,但是缺少了相当多的天,我想使用 SQL 找出丢失的天,我有什么想法如何编写这个查询吗?
我怀疑您通过某种方式获取日期列表并将其与数据库中的值进行比较来解决此问题。
我知道您可以使用 PHP 或其他编程语言使用多个查询来执行此操作,但如果可能的话,我希望在数据库级别执行此操作。
提前致谢
最佳答案
对于 PostgreSQL,使用generate_series() 函数动态生成“日期列表”非常容易:
with all_dates as (
select cast((current_date - interval '4' month) as date) + i as the_date
from generate_series(0, extract(day from current_date - (current_date - interval '4' month))::int) as i
)
select ad.the_date,
y.id,
y.numOfUsers
from all_dates t
left join your_table y ON y.dateCreated = t.the_date;
关于php - SQL:从数据库中获取所有缺失的日期记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7795073/