问题描述
我有一个看起来像这样的表,我希望能够通过ReportID总结以下内容。 ReportID和类型以及列出的月份下每个月的天数应该有一个清单。我不想弄清楚数据集的开始和结束日期,它应该是自动的。
[
。
[
解决方法
如果您使用的是Sql server
,则需要计算ReportId内的Startdate和EndDate之间的天数,而不是使用window function sum
和datetime function datediff
(数天):
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,EndDate))
over (partition by ReportId,Type order by StartDate rows unbounded preceding) count_days_rep_type
from Table
编辑:
首先,我们计算开始日期和结束日期的天数,然后使用Cross apply
在同一列中获取天数。
之后,只需为每个 ReportId,Type summing values
:
(写评论):
--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,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,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
希望您能体谅我的努力。