我有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
我想要做的是将结果集返回到不同的列中,我尝试了以下但是得到了#34;没有列名为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 :(得分:1)
当您使用union
时,第一个查询中的列名或别名将用于结果集。在您的情况下,结果集将包含mg_orders
和csv1
作为列标题。
我假设您正在寻找类似于
的查询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