我有两个不同的查询,它们具有完全相同的SELECT和WHERE条件,但它们具有不同的JOIN条件。
我正试图找到一种将这两者结合到一个查询中的方法,而我唯一能够想到的就是使用UNION。有什么不同的或者更好的方法来完成同样的事情吗?
下面是我想要做的事情的一个例子:
create table #Account
(
ID int,
FirstName varchar(25),
LastName varchar(25),
CodeA int,
CodeB int
)
create table #AccountMap
(
CodeA int,
CodeB int,
MapType varchar(25)
)
insert into #Account
values (1, 'Bob', 'Smith', 424, 867), (2, 'John', 'Davis', 543, NULL), (3, 'Mary', 'Brown', 654, 345)
insert into #AccountMap
values (424, 867, '1-1'), (543, NULL, 'A Only'), (654, 345, '1-1'), (NULL, 391, NULL)
-- Query #1
select ID, MapType
from #Account A
join #AccountMap M on M.CodeA = A.CodeA and M.CodeB = A.CodeB
where MapType is not null
-- Query #2
select ID, MapType
from #Account A
join #AccountMap M on M.CodeA = A.CodeA
where MapType is not null
-- Combined results
select ID, MapType
from #Account A
join #AccountMap M on M.CodeA = A.CodeA and M.CodeB = A.CodeB
where MapType is not null
union
select ID, MapType
from #Account A
join #AccountMap M on M.CodeA = A.CodeA
where MapType is not null
drop table #Account, #AccountMap我想要的输出是我提供的示例中组合查询的结果(这是两个查询的不同组合)。
发布于 2019-02-25 16:30:03
像这样怎么样?
这会给你第一个当它存在的时候,第二个当它不存在的时候。
Select ID, COALESCE(M1.MapType, M2.MapType) as MapType
from #Account A
left join #AccountMap M1 on M1.CodeA = A.CodeA and M1.CodeB = A.CodeB
left join #AccountMap M2 on M2.CodeA = A.CodeA
where COALESCE(M1.MapType, M2.MapType) is not null发布于 2019-02-25 16:39:40
你可以试试这个。
Select ID,MapType from #account a left Join #AccountMap b
on a.CodeA=b.CodeA
or a.CodeB=b.CodeBhttps://stackoverflow.com/questions/54870615
复制相似问题