2016-12-02 120 views
0

如果沒有示例,此問題很難解釋。針對一對多關係的單個SQL SELECT查詢

我有2個表,公司員工,他們有一個一對多的關係,一個公司可以參加很多員工。

最簡單的表結構如下所示

Company 
| id | name | 

Employee 
| id | name | company_id | join_date | 

現在的問題是:

我怎麼會選擇第2名員工,並展示自己的加盟日期爲公司表列?

所以結果看起來像這樣

| id | company_name | first_employee_join_at | second_employee_join_at | 
+1

你是什麼意思*前兩名*員工? –

+0

「我認爲前兩名員工是那些首先加入公司的人,對吧?你能提供列定義嗎? – actc

+0

公司和員工如何鏈接?有什麼地方有'company_id'嗎? –

回答

2

假設有在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;