2016-05-11 78 views
0

我有4個不同的選擇狀態,它們將結果聯合起來並像這樣顯示訂單。將聯合查詢返回到多列

lab_orders    MED111 
lab_orders    MED262383 
mg_orders    MED262383 
mg_orders    UNT222 
pcg_pharmacogenetics MED262371 
pcg_pharmacogenetics UNT248234 
well_wellness   UST601061 
well_wellness   UNTAccession 
well_wellness   UST333 

使用此查詢。

select 'mg_orders',csv as csv1 
from (select csv from csvdata where csv not in(select orderid from mg_orders)) as t1 
union 
select 'lab_orders',csv as csv2 
from (select csv from csvdata where csv not in(select orderid from lab_orders)) as t2 
union 
select 'pcg_pharmacogenetics',csv as csv3 
from (select csv from csvdata where csv not in(select orderid from pcg_pharmacogenetics)) as t3 
union 
select 'well_wellness',csv as csv4 
from (select csv from csvdata where csv not in(select orderid from well_wellness)) as t4 

我想要做的是返回結果在單獨的列設置,我曾嘗試以下,但得到「沒有指定的列CSV2」

select csv1, csv2, csv3, csv4 
from(
select 'mg_orders',csv as csv1 
from (select csv from csvdata where csv not in(select orderid from mg_orders)) as t1 
union 
select 'lab_orders',csv as csv2 
from (select csv from csvdata where csv not in(select orderid from lab_orders)) as t2 
union 
select 'pcg_pharmacogenetics',csv as csv3 
from (select csv from csvdata where csv not in(select orderid from pcg_pharmacogenetics)) as t3 
union 
select 'well_wellness',csv as csv4 
from (select csv from csvdata where csv not in(select orderid from well_wellness)) as t4 
) as t 


    lab_orders  mg_orders  pcg_pharmacogenetics    
    MED111   MED262383  MED262371 
    MED262383  UNT222  UNT248234 
+0

你想要的結果集看起來像這不是很清楚,我的查詢。 –

+0

我添加了我想要的結果,看起來像在底部。 – user2168066

+0

well_wellness發生了什麼事。 –

回答

1

當您使用union,該列 - 第一個查詢的名稱或別名將用於結果集。在你的情況下,結果集將包含mg_orderscsv1作爲列標題。

我假定你正在尋找類似的

select 
max(case when csv not in(select orderid from mg_orders) then csv end) as csv1, 
max(case when csv not in(select orderid from lab_orders) then csv end) as csv2, 
max(case when csv not in(select orderid from pcg_pharmacogenetics) then csv end) as csv3, 
max(case when csv not in(select orderid from well_wellness) then csv end) as csv4 
from csvdata 
+0

那麼我可以在第一個查詢中別名從其他結果集的列嗎? – user2168066

+0

這工作,必須拿出'最大'來顯示所有的記錄。謝謝 – user2168066