开发者社区> 问答> 正文

根据行值合并表

下面是我的表结构。

declare @t1 table (id int identity,val int not null,datatype1  int null,datatype2  int null,datatype3  int null,datatype4  int null,type int)
declare @t2 table (id int identity,val int not null,datatype1  int null,datatype2  int null,datatype3  int null,datatype4  int null,type int)
insert into @t1 values (10,1,0,0,0,1),(31,1,0,0,0,1),(20,1,0,0,0,1),(30,1,0,0,0,1)
insert into @t2 values (31,0,1,0,0, 2),(4,0,0,1,0,3),(12,0,0,0,1,4),(31,0,0,0,1,4)

select * from @t1; select * from @t2; 我将2表数据与下面的查询。

select val,max(datatype1) datatype1,max(datatype2)datatype2,max(datatype3)datatype3,max(datatype4)datatype4 from (
select * from @t1

union all

select * from @t2 ) as data group by val 我需要更改逻辑,如果val是@ t2中的val是31并且type = 2,对于这些情况,我需要为val 31获得2行,而其他情况下仅需要不同的值

预期结果:

val datatype1 datatype2 datatype3 datatype4 4 0 0 1 0 10 1 0 0 0 12 0 0 0 1 20 1 0 0 0 30 1 0 0 0 31 1 0 0 1 31 0 1 0 0 --- only if in @t2 val =31 and type=2 请让我仅需更改值31和type = 2即可

展开
收起
祖安文状元 2020-01-04 14:54:18 445 0
1 条回答
写回答
取消 提交回答
  • 根据提供的数据,CASE表达式似乎是可行的方法:

    select val,
      max(datatype1) datatype1,
      max(datatype2) datatype2,
      max(datatype3) datatype3,
      max(datatype4) datatype4 
    from (
      select 't1' AS tab_name, * from @t1
      union all
      select 't2' AS tab_name, * from @t2
     ) as data 
    group by val, CASE WHEN tab_name = 't2' and val=31 and type=2 THEN 1 END; 
                  -- creating subgroup for this specific conditions
    
    2020-01-04 14:54:36
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
RowKey与索引设计:技巧与案例分析 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载