我有下表
Log
Date date
Description varchar
ID integer
以日期作为参数,我必须找到号码。或者每天从开始日期到使用递归cte。后的一个月记录的日志数 有些天可能没有任何日志,所以我必须将计数打印为0。
例如:
select * from Log
返回
1 insert 2011-01-17
2 blah blah 2011-01-23
3 blah 2011-07-07
对于2011-01-17作为输入,输出应为
2011-01-17 1
2011-01-18 0
2011-01-19 0
....
2011-01-23 1
.....
2011-02-17 0
我必须使用 recursive cte 来执行此操作。我不知道如何在每次递归中将日期递增1以及如何停止\终止递归。
这是我到目前为止所做的事情:
with cte as (
select '2011-01-17' as dat,count(*) as count
from log group by date
having date='2011-01-17'
union all
select dateadd(day,1,dat) as dat,count(*) as count
from log,cte
group by date
having date=dateadd(day,1,dat)
where dat<'2011-02-17'
)
select * from cte
答案 0 :(得分:5)
WITH days (d, maxd) AS
(
SELECT MIN(date), MAX(date)
FROM log
UNION ALL
SELECT DATEADD(day, 1, d), maxd
FROM days
WHERE d < maxd
)
SELECT d, COUNT(id)
FROM days
LEFT JOIN
log l
ON l.date = d
GROUP BY
d