如果您正在使用Sql server 并且您需要在 ReportId 中计算 Startdate 和 EndDate 之间的天数,而不是使用 window function sum 和 datetime function datediff(计算天数): p>
select Type,ReportID,sum(datediff(dd,StartDate,EndDate))
over (partition by ReportId order by StartDate rows unbounded preceding)count_days_rep
from Table
或者如果您需要在 ReportId 和类型中汇总计数天数:
select Type,ReportID,sum(datediff(dd,StartDate,EndDate))
over (partition by ReportId,Type order by StartDate rows unbounded preceding) count_days_rep_type
from Table
编辑:
首先,我们计算 startdate 和 enddate 的天数,然后使用Cross apply 在一列中获取天数。
之后,每个 ReportId,Type 只需 summing values:
(写 cmets):
--counting days for each month group by ReportId,Type
select ReportId,Type,Tab.month_num,
sum(Tab.count_days)count_days
from
(
select *,
--startdate: if startdate's month=enddate's month then difference between days
--ELSE count report days for startdate (counting days from this date to the end of the month)
case when datepart(month,StartDate)=datepart(month,EndDate) then datediff(dd,StartDate,EndDate)+1
else datepart(dd,EOMONTH(StartDate))-datepart(dd,StartDate)+1 end CountStartDays,
--stardate's month
datename(month,StartDate)MonthStartDate,
--enddate: if startdate's month=enddate's month then 0 (because this value taken into account already in CountStartDays) ELSE count report days for enddate
--(counting days from the begginning of enddate's month till date)
case when datepart(month,StartDate)=datepart(month,EndDate) then 0 else datepart(dd,EndDate) end CountEndDays,
--enddate's month
datename(month,EndDate)MonthEndDate
from Table
)y
CROSS APPLY
(values (MonthStartDate,CountStartDays),
(MonthEndDate, CountEndDays) ) Tab (month_num,count_days)
group by Type,ReportId,Tab.month_num
希望你能欣赏我的努力。