使用 WINDOW 函数减去 Postgresql 中的行
Subtract Rows in Postgresql using WINDOW functions
我有以下 table 叫 "Projects":
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 之间的差异等于 table.If 和 End_Date 任务中每一行的 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"
我有以下 table 叫 "Projects":
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 之间的差异等于 table.If 和 End_Date 任务中每一行的 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"