假設有在employee
表的外鍵列company_id
:
with emps as (
select id, name, company_id,
row_number() over (partition by company_id order by join_date) as rn
from employee
)
select c.id, c.name as company_name,
e1.join_date as first_employee_join_at,
e2.join_date as second_employee_join_at
from company c
left join emps e1 on e1.company_id = c.id and e1.rn = 1
left join emps e2 on e2.company_id = c.id and e2.rn = 2;
這不會是非常有效的,但。一個稍微更高效的版本將使用條件聚合:
with emps as (
select id, name, company_id,
row_number() over (partition by company_id order by join_date) as rn
from employee
)
select c.id, c.name as company_name,
max(e.join_date) filter (where rn = 1) as first_employee_join_at,
max(e.join_date) filter (where rn = 2) as second_employee_join_at
from company c
join emps e on e.company_id = c.id and e.rn in (1,2)
group by c.id, c.name;
你是什麼意思*前兩名*員工? –
「我認爲前兩名員工是那些首先加入公司的人,對吧?你能提供列定義嗎? – actc
公司和員工如何鏈接?有什麼地方有'company_id'嗎? –