记录来自哪个表以及是否有多个表

时间:2016-06-29 13:06:36

标签: sql sql-server-2005

我在每个表格中有4个表格(Table1Table4)和列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

1 个答案:

答案 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