use recursive common table expressions like a while loop
i have the following table
Log
Date date
Description varchar
ID integer
Given a date as a parameter,i have to find the no. or count of logs logged each day from start date to a month after it using recursive cte. Some Days may have not any logs,so i have to print the count as 0.
ex:
select * from Log
returns
1 insert 2011-01-17
2 blah blah 2011-01-23
3 blah 2011-07-07
For 2011-01-17 as input,the output should be
2011-01-17 1
开发者_开发技巧2011-01-18 0
2011-01-19 0
....
2011-01-23 1
.....
2011-02-17 0
I have to use recursive cte to do that.i don't know how to increment the date by 1 in each recursion and how to stop\terminate the recursion.
This is the thing i have done so far:
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
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
精彩评论