SQL汇总数据集中每个月的天数

问题描述

我有一个看起来像这样的表,我希望能够通过ReportID总结以下内容。 ReportID和类型以及列出的月份下每个月的天数应该有一个清单。我不想弄清楚数据集的开始和结束日期,它应该是自动的。

[

Results1

[

Sample Table2

解决方法

如果您使用的是Sql server,则需要计算ReportId内的Startdate和EndDate之间的天数,而不是使用window function sumdatetime 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          

希望您能体谅我的努力。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...