zoukankan      html  css  js  c++  java
  • 对sql作业的总结(PostgreSQL的递归查询)

    已知条件如下:

    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 排好。

    结果如下:

  • 相关阅读:
    OS模块功能
    read()、readline()、readlines()区别
    【ML-0-2】矩阵求导-定义法和微分法
    【ML-0-1】矩阵求导-定义和求导布局
    博客园转文章的方法
    风格迁移论文--Arbitrary style transfer in real-time with adaptive instance normalization
    【TF-3-2】Tensorflow-mnist的手写识别
    【TF-3-1】Tensorflow--简单线性拟合
    图像分割简介
    图像表示与图像处理的基本概念
  • 原文地址:https://www.cnblogs.com/northernmashiro/p/8874468.html
Copyright © 2011-2022 走看看