如何计算SQL Server中每天的计划中的数字任务?

时间:2016-10-22 17:25:12

标签: sql sql-server date schedule

我正在尝试在SQL Server中创建一个将每天返回任务数量的查询。如果任务的开始和结束日期在同一天,那么它应该只向计数添加一个。

以下是一个小示例数据集:

+----+------------+-------------+
| ID | Start_Date | Finish_Date |
+----+------------+-------------+
|  1 | 24-Oct-16  | 24-Oct-16   |
|  2 | 24-Oct-16  | 26-Oct-16   |
|  3 | 25-Oct-16  | 26-Oct-16   |
|  4 | 26-Oct-16  | 27-Oct-16   |
|  5 | 26-Oct-16  | 28-Oct-16   |
+----+------------+-------------+

这是预期的结果:

+-----------+----------------+
|   Date    | Count_Of_Tasks |
+-----------+----------------+
| 24-Oct-16 |              2 |   
| 25-Oct-16 |              2 |
| 26-Oct-16 |              4 |
| 27-Oct-16 |              2 |
| 28-Oct-16 |              1 |
+-----------+----------------+

任何人都可以创建一个可以计算每天任务数量的示例查询吗?

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

您需要calendar表来执行此操作

我已使用Recursive CTE动态生成开始日期和结束日期范围之间的日期。但是在数据库中创建Calendar表总是更好。这样的查询会非常有用

;with data as
(
select * from (
VALUES
    (1, '2016-10-24 00:00:00', '2016-10-24 00:00:00'),
    (2, '2016-10-24 00:00:00', '2016-10-26 00:00:00'),
    (3, '2016-10-25 00:00:00', '2016-10-26 00:00:00'),
    (4, '2016-10-26 00:00:00', '2016-10-27 00:00:00'),
    (5, '2016-10-26 00:00:00', '2016-10-28 00:00:00')) tc ([ID], [Start_Date], [Finish_Date])
),calendar
     AS (SELECT dates = CONVERT(DATETIME, '24-Oct-16') -- Min Start_Date 
         UNION ALL
         SELECT dates = Dateadd(DAY, 1, dates)
         FROM   calendar
         WHERE  dates < '28-Oct-16') -- Max Finish_Date 
SELECT c.dates,
       Count(s.Start_Date) AS Count_Of_Tasks
FROM   calendar c
       LEFT JOIN data s
              ON c.dates between s.Start_Date and s.Finish_Date
Group by c.dates

结果:

╔═════════════════════════╦════════════════╗
║          dates          ║ Count_Of_Tasks ║
╠═════════════════════════╬════════════════╣
║ 2016-10-24 00:00:00.000 ║              2 ║
║ 2016-10-25 00:00:00.000 ║              2 ║
║ 2016-10-26 00:00:00.000 ║              4 ║
║ 2016-10-27 00:00:00.000 ║              2 ║
║ 2016-10-28 00:00:00.000 ║              1 ║
╚═════════════════════════╩════════════════╝

答案 1 :(得分:0)

这很棘手。一种方法分解数据并使用运行总和重新聚合:

select dte,
       sum(sum(inc)) over (order by dte) as total
from ((select start_date as dte, 1 as inc
       from example
      ) union all
      (select dateadd(day, 1, finish_date), -1 as inc
       from example
      )
     ) e
group by dte

答案 2 :(得分:0)

SELECT DISTINCT(startdate),
       (
           SELECT COUNT(*)
           FROM   tasks AS b
           WHERE  a.startdate BETWEEN b.startdate AND b.enddate
       )
FROM   tasks AS a 
UNION
SELECT DISTINCT(enddate),
       (
           SELECT COUNT(*)
           FROM   tasks AS b
           WHERE  a.enddate BETWEEN b.startdate AND b.enddate
       )
FROM   tasks AS a