[英]Conditional join to two different tables based on 2 columns in 1 table
我有一张看起来像这样的桌子
dbo.Box
ID SourceID OverrideQueueID
1 1 NULL
2 1 2
3 2 NULL
我需要找出一种方法来说明OverrideQueueID是否为NULL,然后从dbo.Box到dbo.Source.ID进行联接,否则,如果OverrideQueueID不是NULL则加入dbo.Queue.ID。 因为它要连接到不同的表,所以可以一次选择吗?
我试图做到这一点,如果可能的话,不引入一堆左联接。
我希望工会能为您提供帮助,如下所示。
Select Col1,Col2
From dbo.Box B
Join dbo.Source S On S.Id = b.SourceID
Where B.OverrideQueueID is Null
Union
Select Col1,Col2
From dbo.Box B
Join dbo.Queue Q On Q.Id = b.SourceID
Where B.OverrideQueueID is Not Null
一种可能的方式:
select * from Box as a
join Box as b ON a.OverrideQueueID is null and a.ID = b.SourceID
join Queue as q ON a.OverrideQueueID is not null and a.ID = q.ID
尝试这个。 您可以修改WHERE子句以适合您的需求。
SELECT
b.*,
s.*,
q.*
FROM
dbo.Box b
LEFT JOIN dbo.[Source] s ON s.ID = b.SourceID AND b.OverrideQueueID IS NULL
LEFT JOIN dbo.[Queue] q ON q.ID = b.OverrideQueueID AND b.OverrideQueueID IS NOT NULL
WHERE
s.ID IS NOT NULL OR q.ID IS NOT NULL
select *,a. form box b
inner join (select OverrideQueueID ,SourceID
from box where OverrideQueueID is null)a
on b.id=a.SourceID
inner join dbo.Queue.ID a
where b.OverrideQueqeID is not null
on B.ID = Q.ID
您有两个SourceID = 1的记录。一个为NULL,另一个为替代。 哪一个获胜,我将假定为#2 ID,但应该有更高的数字作为前提吗?
由于您可能关注每个源,因此它应该像max()一样简单,并且根本没有任何连接...类似
select
b.SourceID,
max( coalesce( b.OverrideQueueID, b.ID )) as FinalQueue
from
Box b
group by
b.SourceID
应用的合并基本上将采用任何覆盖队列,并仅用其自己的源替换它们。 因此,对于记录1和3,它们将指向自己作为要应用的队列1和3。 仅在有两个记录的sourceID = 1上,#2队列才会取代#1(NULL覆盖)队列。
dbo.Box
ID SourceID OverrideQueueID Coalesce value
1 1 NULL 1
2 1 2 2
3 2 NULL 3
因此,sourceID = 1的最大值将是队列2,而SourceID = 2的最大值将是队列3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.