2016-05-07 72 views
-1

我卡住了。我有2張桌子 - 看圖像1 Table columns而我想建立查詢,這會給我的結果 - 它顯示在圖像沒有2. the result of query結合不同表格的列值

我有2個查詢,我想混合起來,從圖像2號獲取列表。請幫助我,如何構建查詢。

  • 查詢編號1:SELECT department_name,department_id FROM DEPARTMENTS WHERE department_id between 90 AND 110;
  • 查詢編號2:從僱員處選擇last_name,department_id WHERE department_id在90和110之間;從我的樣表

回答

1

查詢

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...

+0

很棒的回答。我從來沒有使用UNION,可能是我沒有意識到使用的原因。感謝您提供更好的答案。 –

+0

謝謝mathguy爲你提供幫助。這個答案就是我問的。 –

0
SELECT c.last_name, 
     d.department_id, 
     d.department_name 
FROM employee c 
JOIN deptartment d ON d.department_id=c.department_id 
WHERE d.department_id BETWEEN 90 AN 110 

輸出

+-------+----+------------+ 
| KING | 10 | ACCOUNTING | 
| BLAKE | 30 | SALES  | 
| CLARK | 10 | ACCOUNTING | 
| JONES | 20 | RESEARCH | 
| SCOTT | 20 | RESEARCH | 
+-------+----+------------+ 
+0

謝謝,是否有任何可能性以不同的方式列出? DEPARTMENT_NAME ------ DEPARTMENT_ID ____________________________________________ 與以下LAST_NAME名單 –

+0

不同,如何? –

+0

@PirateX - 當然你可以,你只需要知道如何去做。我會盡快發佈解決方案。 – mathguy

相關問題