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

    结果如下:

  • 相关阅读:
    Linux上的文件管理类命令都有哪些,其常用的使用方法及其相关示例演示
    总结软连接和硬连接区别,并用实例操作说明
    描述文件的元数据信息有哪些,分别表示什么含义,如何查看?如何修改文件的时间戳信息?
    Git Shell push_code 脚本
    YDD的铁皮锅——C/C++内存概念
    Linux Shell 常见用法及问题
    MFC 设置鼠标样式(SetSystemCursor函数问题)
    Qt QTableView自定义列表(插入图片)
    Github libinjection库研究总结
    Windows/Linux:VMware虚拟机用内网IP通讯
  • 原文地址:https://www.cnblogs.com/northernmashiro/p/8874468.html
Copyright © 2011-2022 走看看