对于每个有受抚养人的雇员,请列出其姓氏和最老的受抚养人的姓名。按受抚养者姓名顺序显示结果

时间:2019-02-01 00:01:50

标签: sql

SELECT E.Lname,D.Dependent_name
FROM EMPLOYEE as E , DEPENDENT as D 
WHERE 
E.ssn=D.Essn
  AND 
 D.Bdate = (SELECT MIN(Bdate) FROM DEPENDENT
           WHERE Bdate IS NOT NULL)

这确实有效,但仅显示1名员工

链接到数据库: https://www.db-fiddle.com/f/xhEj2sAgdTMABBkCtJvmoC/0#&togetherjs=z3CKywAccH

2 个答案:

答案 0 :(得分:0)

实际上,您的子查询返回整个表中的最小bdate,从而仅过滤出具有最老依赖项的员工。@ PM77-1注释,您需要将子查询与员工相关联您当前正在处理。

SELECT E.Lname,D.Dependent_name
FROM 
    EMPLOYEE as E
    INNER JOIN DEPENDENT as D ON E.ssn=D.Essn
WHERE D.Bdate = (
   SELECT MIN(Bdate) 
   FROM DEPENDENT
   WHERE Essn = E.ssn
)
ORDER BY 2, 1;

另一种可能更有效的选择是使用Postgres窗口函数ROW_NUMBER()为行中的每个记录分配行号,该记录是由给定雇员的所有家属组成的,按出生日期排序。然后,外部查询可以过滤每个组中的第一条记录:

SELECT x.lname, x.dependent_name
FROM (
    SELECT
        e.lname, 
        d.dependent_name,
        ROW_NUMBER() OVER(PARTITION BY e.ssn ORDER BY d.bdate) rn
    FROM employee e
    INNER JOIN dependent d ON e.ssn = d.essn
) x WHERE x.rn = 1
ORDER BY 2, 1;

Demo on DB Fiddle

答案 1 :(得分:0)

select a.lname, a.dependent_name 
from 
(
     select e.lname, d.dependent_name, d.bdate, e.ssn
     from employee e, dependent d
     where e.ssn=d.essn
     order by d.dependent_name, e.lname
)a
where a.bdate= (select min(bdate) from dependent 
                where dependent.essn= a.ssn)
order by a.lname;

这将显示三名雇员的姓名> Smith,Wallace,Wong及其相应的长子家属> Elizabeth,Abner,Joy。

希望这可以解决问题。