我在每个表格中有4个表格(Table1
到Table4
)和列CODE
。我使用UNION ALL
来确定它们来自哪里
select distinct CODE, 'Table1' from Table1 where TABLE1_EFF_STARt >= '01/01/2014'
union all
select distinct CODE, 'Table2' from Table2 where TABLE2_EFF_STARt >= '01/01/2014'
union all
select distinct CODE, 'Table3' from Table3 where TABLE3_EFF_STARt >= '01/01/2014'
union all
select distinct CODE, 'Table4' from Table4 where TABLE4_EFF_STARt >= '01/01/2014'
有时同一个CODE
可以在多个表中,我想识别并以下表格形式返回结果。当我在多个表中的代码时,我想在Y
列中将其标记为Multisource
。
CODE Table1 Table2 Table3 Table4 Multisource
12345 Y N N N N
34233 Y Y N N Y
45345 Y N N N N
23417 Y N Y N Y
45346 Y N N N Y
答案 0 :(得分:1)
一种方法是使用conditional aggregation
来展示您的搜索结果:
select code,
max(case when tbl = 'Table1' then 'Y' else 'N' end) 'Table1',
max(case when tbl = 'Table2' then 'Y' else 'N' end) 'Table2',
max(case when tbl = 'Table3' then 'Y' else 'N' end) 'Table3',
max(case when tbl = 'Table4' then 'Y' else 'N' end) 'Table4',
case when count(*) > 1 then 'Y' else 'N' end 'Multisource'
from (
select distinct CODE, 'Table1' as tbl from Table1 where TABLE1_EFF_STARt >= '01/01/2014'
union all
select distinct CODE, 'Table2' from Table2 where TABLE2_EFF_STARt >= '01/01/2014'
union all
select distinct CODE, 'Table3' from Table3 where TABLE3_EFF_STARt >= '01/01/2014'
union all
select distinct CODE, 'Table4' from Table4 where TABLE4_EFF_STARt >= '01/01/2014'
) t
group by code