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

    结果如下:

  • 相关阅读:
    C#串口通信程序SerialPort类
    51单片机和PC串口异步通信
    Robotics ToolBox机械臂仿真
    51单片机和PC串口异步通信(续)
    谈谈FFT有何用
    volatile关键字的使用
    如何走好后面的路
    51单片机液晶显示计时器
    IDE86汇编语言环境使用
    不使用跳转的宏CV_IMIN分析
  • 原文地址:https://www.cnblogs.com/northernmashiro/p/8874468.html
Copyright © 2011-2022 走看看