AS PREPARATION, you need to generate a list of dates. There are multiple ways for that. One is a recursive CTE. For example, this one creates a list of the last 15 days:
with datelist ([date]) as
(
select dateadd(dd, -15, cast(getdate() as date)) as [date] -- 15 days back
union all
select dateadd(dd, 1, [date]) from datelist where dateadd(dd, 1, [date]) <= getdate()
)
select * from datelist option (maxrecursion 400)
FOR THE FINAL SOLUTION, you now need to create a LEFT JOIN
between the datelist
and with a subquery with your user
table.
An overall solution for your question therefore goes as follows.
I have also put everything together in a SQLFiddle:
http://sqlfiddle.com/#!3/36510/1
with datelist ([date]) as
(
select dateadd(dd, -15, cast(getdate() as date)) as [date] -- 15 days back
union all
select dateadd(dd, 1, [date]) from datelist where dateadd(dd, 1, [date]) <= getdate()
)
select 'cricket' as activity,
d.[date],
coalesce(SUM(datediff(second, u.starttime, u.endtime)/60.0), 0)
as TimePerDay
from datelist d
left join
(
select [starttime], [endtime], cast(starttime as date) as [date]
from [users]
where activity='cricket' and email='abc'
) u
on d.[date] = u.[date]
group by d.[date]
option (maxrecursion 400)
So this query will give you the table for the cricket activity of the last 15 days of one specific user.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…