我有两个表,ActiveContacts和CompletedContacts。 ActiveContacts包含尚未关闭的联系人,但可能由CompletedContacts中的联系人产生。
我需要找到ActiveContacts中所有联系人的最小ContactStart,一直到CompletedContacts中的第一个相关联系人(如果存在)。您知道当ContactID = MasterContactID时,您已到达“根”。
例如,在我的示例数据中:
From ActiveContacts
45227565918 --> 45130250258
From CompletedContacts
45130250258 --> 45065182801
45065182801 --> 45065111275
45065111275 --> 44987017334
44987017334 --> 44986804829
44986804829 --> 44986804829 --> 2019-02-25 07:48:00.00
在某些情况下,ContactID仅存在于ActiveContact上,因为它不是从CompletedContacts上的其他联系人衍生而来的。
45562514264 --> 45562514264 --> 2019-03-27 02:44:00.000
我认为这可以通过递归CTE来实现,但我做对了。这可能吗?我唯一的另一个想法是逐行游标类型的情况。
下面的示例代码。
CREATE TABLE CustServ.WF.ActiveContactsTest
(
ContactID [bigint],
MasterContactID [bigint],
ContactStart [datetime]
);
INSERT INTO CustServ.WF.ActiveContactsTest (ContactID, MasterContactID, ContactStart)
VALUES
(45227565918,45130250258,'3/8/19 17:29'),
(45547409273,45545833249,'3/26/19 19:44'),
(45547477525,45547474793,'3/26/19 22:45'),
(45547491195,45547491195,'3/26/19 23:27'),
(45562514264,45562514264,'3/27/19 2:44');
CREATE TABLE CustServ.WF.CompletedContactsTest
(
ContactID [bigint],
MasterContactID [bigint],
ContactStart [datetime]
);
INSERT INTO CustServ.WF.CompletedContactsTest (ContactID, MasterContactID, ContactStart)
VALUES
(45130250258,45065182801,'3/4/19 17:22'), -- From 1st row in ActiveContacts
(45065182801,45065111275,'2/28/19 14:11'),
(45065111275,44987017334,'2/28/19 13:49'),
(44987017334,44986804829,'2/25/19 9:20'),
(44986804829,44986804829,'2/25/19 7:48'),
(45545833249,45510675166,'3/26/19 9:44'), -- From 2nd row in ActiveContacts
(45510675166,44056741709,'3/25/19 9:35'),
(44056741709,45435906188,'3/21/19 18:50'),
(45435906188,45370464489,'3/20/19 17:15'),
(45370464489,45318017172,'3/18/19 15:31'),
(45318017172,45280077660,'3/14/19 13:16'),
(45280077660,45280077660,'3/12/19 13:24'),
(45547474793,45547474793,'3/26/19 22:31'); -- From 3rd row in ActiveContacts
答案 0 :(得分:0)
这是一个混乱的数据模型,具有在两个表中表示的链接。但是您可以这样做:
with t as (
select contactID, MasterContactID, ContactStart, 0 as isactive
from CompletedContactsTest
-- where contactID = MasterContactID
union all
select contactID, MasterContactID, ContactStart, 1 as isactive
from ActiveContactsTest
-- where contactID = MasterContactID
),
cte as (
select contactID, MasterContactID, ContactStart, 1 as lev, isactive
from t
where contactID = MasterContactID
union all
select t.contactID, cte.MasterContactID, cte.ContactStart, lev + 1, t.isactive
from t join
cte
on t.contactID = cte.MasterContactID
where t.contactID <> t.MasterContactID
)
select contactid, min(contactstart)
from cte
where isactive = 1
group by contactid;
Here是db <>小提琴。