gpt4 book ai didi

sql-server - 根据行值联合表

转载 作者:行者123 更新时间:2023-12-04 10:50:13 24 4
gpt4 key购买 nike

下面是我的表结构。

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

如果 @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

最佳答案

根据提供的数据看起来像 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

db<>fiddle demo

关于sql-server - 根据行值联合表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59517117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com