簡體   English   中英

合並具有不同加入條件的兩個查詢

[英]Combine Two Queries With Different Join Conditions

我有兩個具有完全相同的SELECTWHERE條件的不同查詢,但是它們具有不同的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

我想要的輸出是我提供的示例中組合查詢的結果(兩個查詢的不同組合)。

這樣怎么樣

這將為您提供第一個(如果存在)和第二個(不存在)。

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

你可以試試看

Select ID,MapType from #account a left Join #AccountMap b 
on a.CodeA=b.CodeA 
or a.CodeB=b.CodeB

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM