1

我有下表称为“项目”:

CREATE TABLE Projects (Task_ID integer, Start_Date date, End_Date date)

INSERT INTO Projects VALUES
(1, '2015-10-01', '2015-10-02'),
(2, '2015-10-02', '2015-10-03'),
(3, '2015-10-03', '2015-10-04'),
(4, '2015-10-13', '2015-10-14'),
(5, '2015-10-14', '2015-10-15'),
(6, '2015-10-28', '2015-10-29'),
(7, '2015-10-30', '2015-10-31')

保证表中每一行的End_Date和Start_Date之间的差等于1天。如果任务的End_Date是连续的,那么它们是同一个项目的一部分。我需要编写一个查询来输出项目的开始日期和结束日期,这些日期按升序完成项目所需的天数列出。如果有多个项目具有相同的完成天数,则应按项目开始日期排序。

4

1 回答 1

1

这是解决方案:

WITH results AS 
(
SELECT p.*,
       extract('doy'
FROM p.start_date) AS start_Doy,
     extract('doy'
FROM p.end_date) AS end_Doy,
     ROW_NUMBER() OVER(PARTITION BY COUNT(*)
ORDER BY p.end_date) AS row_num,
         extract('doy'
FROM p.end_date) -(ROW_NUMBER() OVER(PARTITION BY COUNT(*)
ORDER BY p.end_date)) AS DIFF
FROM Projects p
GROUP BY p.task_id,
         p.start_date,
         p.end_date
ORDER BY p.end_date)
SELECT MIN(r.start_date) AS "Project Start Date",
       MAX(r.end_date) AS "Project End Date",
       (MAX(r.end_doy) - MIN(r.start_doy)) AS "Project Duration"
FROM results r
Group BY r.diff
ORDER BY "Project Duration",
         "Project Start Date"
于 2017-10-11T22:27:33.623 回答