条件联合多个表

时间:2019-12-29 14:07:55

标签: sql sql-server

这是基于Union based on condition

declare @t1 table (val int,datatype1  int,datatype2  int ,datatype3  int)
declare @t2 table (val int,datatype1  int ,datatype2  int ,datatype3  int )
declare @t3 table (val int,datatype1  int ,datatype2  int ,datatype3  int )
insert into @t1 values (10,1,0,0),(31,1,0,0),(20,1,0,0)
insert into @t2 values (31,0,1,0),(4,0,1,0)
insert into @t3 values (31,0,0,1),(5,0,0,1);

以下是需求的变化(大小写):

1. need to union @t1,@t2 & @t3 
   (if same value exist @t1 & @t2 multiple rows and @t2 & t3 only 1 row)
2. if any duplicate value (there is no chance dup in same table)

 i) suppose 31 in @t1 , 31 in @t2 then multiple rows are allowed 
 ii) suppose 31 in  @t2 & @t3  then only one records i.e @t3 updated to @t2  
 iii) if 31 in @t1 ,@t2,@t3  only 2 records i.e @t1,@t2 records with @t3 details updated to @t2 records

现在i)和iii)工作正常

select val,
  max(datatype1) datatype1,
  max(datatype2)datatype2,
  max(datatype3)datatype3
from (
  select 't1' AS tab_name, * from @t1
  union all
  select 't2' AS tab_name,* from @t2
   union all
  select 't3' AS tab_name,* from @t3
 ) as data 
group by val,  CASE WHEN tab_name in ('t2')   THEN 1 END
order by val;

但是当前结果显示案例2的多个记录也有帮助

预期结果:

Expected Result

1 个答案:

答案 0 :(得分:1)

您的问题很难回答。我对条件有点迷茫,但是这个相当简单的查询返回您指定的结果:

select val,
       max(datatype1) as datatype1,
       max(datatype2) as datatype2,
       max(datatype3) as datatype3,
       max(datatype4) as datatype4 
from (select 't1' AS tab_name, t1.* from t1
      union all
      select 't2' AS tab_name, t2.* from t2
      union all
      select 't3' AS tab_name, t3.* from t3
     ) data 
group by val;

Here是db <>小提琴。

我想知道您所有结果的最终结果是否是相对简单的汇总。