对sql作业的总结(PostgreSQL的递归查询)

2018-06-17 20:07:23来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

已知条件如下:

CREATE TABLE appointment (
emp_id integer NOT NULL,
jobtitle varchar(128) NOT NULL,
salary decimal(10,2) NOT NULL,
start_date date NOT NULL,
end_date date NULL
);
ALTER TABLE appointment ADD CONSTRAINT pkey_appointment PRIMARY KEY (emp_id, jobtitle, start_date);
ALTER TABLE appointment ADD CONSTRAINT chk_appointment_period CHECK (start_date <= end_date);

插入数据如下:

INSERT INTO appointment VALUES
(1, ’tutor’, 40000, ’2008-01-01’, ’2009-02-01’),
(1, ’tutor’, 42000, ’2009-01-01’, ’2010-09-30’),
(1, ’tutor’, 45000, ’2012-04-01’, ’2013-12-31’),
(1, ’tutor’, 46000, ’2014-01-01’, ’2014-12-31’),
(1, ’lecturer’, 65000, ’2014-06-01’, NULL),
(2, ’librarian’, 35000, ’2014-01-01’, NULL),
(2, ’tutor’, 20000, ’2014-01-01’, NULL),
(3, ’lecturer’, 65000, ’2014-06-01’, ’2015-01-01’);

既:

 问题如下:

Write an SQL query which returns for all current employees the start of their current period of continuous employment. That is, we are asking for the oldest date X such that the employee had one or more appointments on every day since X. 

then the query should return

Hint: First construct a subquery to compute appointments for current employees that do not overlap with (or are adjacent to) appointments (for the same employee) starting earlier then select for each employee the latest start-date of such appointments.

代码如下:

WITH RECURSIVE start_appointment AS (
  SELECT emp_id, start_date
  FROM appointment
  WHERE end_date IS NULL
  UNION
    SELECT a.emp_id, a.start_date
  FROM appointment a, start_appointment sa
  WHERE a.emp_id = sa.emp_id AND
    a.end_date >= (sa.start_date - 1) AND
    a.start_date <= sa.start_date
)
SELECT emp_id, min(start_date) as start_date
FROM start_appointment
GROUP BY emp_id;

Union用于合并两个或多个 SELECT 语句的结果集, UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。

Union 的话只会选取不同的值,添加All的话重复的 不重复的都会选上。

with recursive 是 postgresql 支持的一种写法,既递归查询。

我们现在有两个表,通过null得表a,where条件是一个表的工作截止日期必须比另个表的开始日期大,开始日期还要比下一个表的开始日期要小,这样才能确保是工作时间是连着的,通过递归不断选择我们所需要的数据,最后min一下得到最小值再gruop by 排好。

结果如下:

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:MongDB

下一篇:MongoDB最佳实践中文手册