根据最近的日期联接表

时间:2018-11-30 01:28:56

标签: postgresql join

假设我有三个表:

  • employees,具有列idname
  • salaries,带有列employee_idsalarydate
  • underlings,带有列employee_idnumber_of_underlingsdate

我想连接表,以便对于每个salaries条目,都有一行带有salary值的行,与该行的name关联的employee_id以及number_of_underlings值,该行的date项最近在date的{​​{1}}之前(即,给定员工应具有的下标数量当时他们有给定的工资)。

例如,假设以下行出现在描述的表中:

salaries

然后,结果联接将具有行:

id | name      employee_id | salary  |    date         employee_id | number_of_underlings |    date
---+-------   -------------+---------+------------    -------------+----------------------+------------
13 | Sally              13 |   90000 | 2017-11-29               13 |                    0 | 2017-05-13
                        13 |   95000 | 2018-01-01               13 |                    6 | 2018-02-20
                        13 |  120000 | 2018-03-01

当然,联接 name | salary | number_of_underlings | date -------+---------+----------------------+------------ Sally | 90000 | 0 | 2017-11-29 Sally | 95000 | 0 | 2018-01-01 Sally | 120000 | 6 | 2018-03-01 employees表是微不足道的,但是salaries表又如何呢?

1 个答案:

答案 0 :(得分:1)

一种方法是使用相关子查询:

SELECT
    e.name,
    s.salary,
    (SELECT u.number_of_underlings FROM underlings u
     WHERE e.id = u.employee_id AND s.date >= u.date
     ORDER BY u.date DESC LIMIT 1) number_of_underlings,
    s.date
FROM employees e
INNER JOIN salaries s
    ON e.id = s.employee_id

Demo