查詢:
with departments (department_id, department_name) as (
select 90, 'Executive' from dual union all
select 100, 'Finance' from dual union all
select 110, 'Accounting' from dual
),
employees (employee_id, last_name, department_id) as (
select 1003, 'King' , 90 from dual union all
select 1005, 'De Hann' , 90 from dual union all
select 1009, 'Gietz' , 110 from dual union all
select 1013, 'Popp' , 100 from dual union all
select 1014, 'Chen' , 100 from dual union all
select 1015, 'Higgins' , 110 from dual union all
select 1029, 'Greenberg', 100 from dual union all
select 1040, 'Kochar' , 90 from dual union all
select 1043, 'Faviet' , 100 from dual union all
select 1045, 'Urman' , 100 from dual union all
select 1049, 'Sciarra' , 100 from dual
)
-- end input data; begin actual query --
select c_name, department_id from
(select department_name as c_name, department_id, 0 as categ from departments
union all
select ' ' || last_name as c_name, department_id, 1 from employees
order by department_id, categ, c_name
);
結果:
C_NAME DEPARTMENT_ID
------------- -------------
Executive 90
De Hann 90
King 90
Kochar 90
Finance 100
Chen 100
Faviet 100
Greenberg 100
Popp 100
Sciarra 100
Urman 100
Accounting 110
Gietz 110
Higgins 110
您不需要「with ...」部分;只需使用在兩個分解子查詢(在「輸入數據」之後)之後的SELECT語句開始的查詢。我甚至在每個部門的名字下爲你訂購;如果不需要,只需從ORDER BY子句中刪除「c_name」即可。
我叫了第一列c_name;你可以把它稱爲任何你想要的,但是當它也包含員工姓氏時稱之爲department_name對我來說沒有多大意義。要調用它任何你想要的,將SELECT語句從SELECT c_name, department_id
更改爲SELECT c_name AS whatever, department_id...
很棒的回答。我從來沒有使用UNION,可能是我沒有意識到使用的原因。感謝您提供更好的答案。 –
謝謝mathguy爲你提供幫助。這個答案就是我問的。 –