【问题标题】:SQL Summarizing the number of days in each month from a data setSQL从数据集中总结每个月的天数
【发布时间】:2020-08-26 16:58:26
【问题描述】:

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

[

.

[

【问题讨论】:

  • 样本数据最好显示为formatted text。请参阅here,了解有关如何创建漂亮表格的一些提示。
  • 您使用的是哪个 dbms? (在日期/时间方面,许多产品都符合 ANSI SQL。)
  • 列数据类型?
  • Barb Reinhardt,在标记 EDIT 后尝试新查询
  • jarih:我使用 Microsoft SQL Server Management Studio。

标签: sql date summary


【解决方案1】:

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

编辑:

首先,我们计算 startdateenddate 的天数,然后使用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          

希望你能欣赏我的努力。

【讨论】:

  • 这让我成为了他们的一部分。我需要知道每个月的天数,而不是总天数。
  • Barb Reinhardt,写了查询(在声明编辑之后)
  • Barb Reinhardt,你试试查询吗?
  • 是的,我试过了,但我得到的 ReportID 在选择列表中是无效的,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。我试过把它放在几个地方,但之前没有使用过 CROSS APPLY。
  • 此查询有效。它正在我的数据库上工作。您已经描述了错误,但是如果 ReportId 在 groupby 语句中,它是怎么回事。请检查它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多