在 SQL Server 中,您可以执行以下操作
create procedure dbo.DoSummary(@startdate datetime, @enddate datetime, @dow int)
as
set DateFIRST @dow;
with cte (date) as (
select case
when datepart(dw, @startdate) = 1 then @startdate
else dateadd(d,8-datepart(dw, @startdate), @startdate)
end as date
union all
select dateadd(d,7, date)
from cte where dateadd(d,7,date) < @enddate
)
select
cte.date, count(items.opened) as [Open]
from
cte left outer join items on cte.date >= items.opened and cte.date < coalesce(items.closed, dateadd(d,1,cte.date))
group by cte.date
然后你只需执行
dbo.DoSummary '2001-01-01','2001-07-01', 7
执行。
最后一个参数@dow
控制使用星期几,7 是星期日
更新由于 OP 无权创建存储过程,您可以简单地将函数体用作原始 Sql。我将给出一个使用 c# 中的 ADO 的示例。
using (var conn = new SqlConnection(connectionString)) {
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "set DateFIRST @dow; " +
"with cte (date) as ( " +
"select case " +
"when datepart(dw, @startdate) = 1 then @startdate "+
"else dateadd(d,8-datepart(dw, @startdate), @startdate) " +
"end as date " +
"union all " +
"select dateadd(d,7, date) " +
"from cte where dateadd(d,7,date) < @enddate " +
") " +
"select cte.date, count(items.opened) as [Open] " +
"from cte " +
"left outer join items " +
"on cte.date >= items.opened " +
"and cte.date < coalesce(items.closed, dateadd(d,1,cte.date)) "+
"group by cte.date ";
cmd.Parameters.AddWithValue("@startdate", new DateTime(2001,01,01));
cmd.Parameters.AddWithValue("@enddate", new DateTime(2001,04,01));
cmd.Parameters.AddWithValue("@dow", 7);
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
// do somthing with data
}
}
}
}