简体   繁体   English

使用日期开始日期时间和结束日期时间的 SQL 查询组

[英]SQL query group by using day startdatetime and end datetime

I have the following table Jobs :我有下表Jobs

|Id  | StartDateTime       | EndDateTime
+----+---------------------+----------------------
|1   | 2020-10-20 23:00:00 | 2020-10-21 05:00:00
|2   | 2020-10-21 10:00:00 | 2020-10-21 11:00:00

Note job id 1 spans October 20 and 21.注意作业 ID 1 跨越 10 月 20 日和 21 日。

I am using the following query我正在使用以下查询

SELECT DAY(StartDateTime), COUNT(id)
FROM Job
GROUP BY DAY(StartDateTime)

To get the following output.得到以下输出。 But the problem I am facing is that day 21 is not including job id 1. Since the job spans two days I want to include it in both days 20 and 21.但我面临的问题是第 21 天不包括工作 ID 1。由于工作跨越两天,我想将它包括在第 20 天和第 21 天。

Day | TotalJobs
----+----------
20  | 1
21  | 1

I am struggling to get the following expected output:我正在努力获得以下预期输出:

Day | TotalJobs
----+----------
20  | 1
21  | 2

One method is to generate the days that you want and then count overlaps:一种方法是生成您想要的天数,然后计算重叠:

with days as (
      select convert(date, min(j.startdatetime)) as startd,
             convert(date, max(j.enddatetime)) as endd
      from jobs j
      union all
      select dateadd(day, 1, startd), endd
      from days
      where startd < endd
     )
select days.startd, count(j.id)
from days left join
     jobs j
     on j.startdatetime < dateadd(day, 1, startd) and
        j.enddatetime >= startd
group by days.startd;

Here is a db<>fiddle. 是一个 db<>fiddle。

You can first group by with same start and end date and then group by for start and end date having different start and end date您可以先按具有相同开始和结束日期的分组,然后按具有不同开始和结束日期的开始和结束日期分组

SELECT a.date, SUM(counts) from (
      SELECT DAY(StartDateTime) as date, COUNT(id) counts
      FROM Table1
      WHERE DAY(StartDateTime) = DAY(EndDateTime)
      GROUP BY StartDateTime
      UNION ALL 
      SELECT DAY(EndDateTime), COUNT(id)
      FROM Table1
      WHERE DAY(StartDateTime) != DAY(EndDateTime)
      GROUP BY EndDateTime
      UNION ALL 
      SELECT DAY(StartDateTime), COUNT(id)
      FROM Table1
      WHERE DAY(StartDateTime) != DAY(EndDateTime)
      GROUP BY StartDateTime) a
GROUP BY a.date 
 

Here is SQL Fiddle link SQL Fiddle这是 SQL Fiddle 链接SQL Fiddle

Also replace Table1 with Jobs when running over your db context在您的数据库上下文中运行时,也将 Table1 替换为 Jobs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM