我有2张桌子。一个是存储CID列表的#crecs和存储克隆CVID的#temp1。对于Crecs表中的ID,我想遍历#temp1表以查找max(CVID)并根据条件提取该CID的克隆CVID的日期。
我已经将要求归结为下表:
create table #temp1(cid int,cvid int,flag varchar(5), date1 date, clone int)
insert into #temp1
values ('43','1001','A','1/1/2015',null),
('43','1002','R','2/1/2015',1001),
('43','1003','R','3/1/2015',1002),
('43','1004','R','4/1/2015',1003)
create table #crecs(cid int)
insert into #crecs values(43),(44),(45)
select * from #crecs
select * from #temp1
我的查询:
select t2.cid,max(t2.cvid),t2.clone,t1.cvid,t1.date1
from #temp1 t2 , #temp1 t1
join #crecs c on c.cid = t1.cid
where t2.clone = t1.cvid
and t1.clone is null and t1.flag = 'A'
group by t2.cid,t2.cvid,t2.clone,t1.cvid,t1.date1
drop table #temp1,#crecs
以下是我的rextester链接:
http://rextester.com/GSIG28211
任何帮助?!
答案 0 :(得分:1)
您可以使用递归CTE遍历每个克隆,然后使用MAX()检索最后一个级别并显示它的记录。
;WITH RecursiveClones AS
(
SELECT
CID = C.cid,
OriginalCVID = T.cvid,
ClonedCVID = T.cvid,
Level = 0
FROM
#crecs AS C
LEFT JOIN #temp1 AS T ON C.cid = T.cid
WHERE
NOT EXISTS (SELECT 'does not have a clone' FROM #temp1 AS X WHERE X.cvid = T.clone)
UNION ALL
SELECT
CID = R.cid,
OriginalCVID = R.OriginalCVID,
ClonedCVID = T.cvid,
Level = R.Level + 1
FROM
RecursiveClones AS R
INNER JOIN #temp1 AS T ON R.ClonedCVID = T.clone
),
LastCloneByCID AS
(
SELECT
R.CID,
MaxLevel = MAX(R.Level)
FROM
RecursiveClones AS R
GROUP BY
R.CID
)
SELECT
L.CID,
R.ClonedCVID,
R.OriginalCVID,
T.date1
FROM
LastCloneByCID AS L
LEFT JOIN RecursiveClones AS R ON
L.CID = R.CID AND
L.MaxLevel = R.Level
LEFT JOIN #temp1 AS T ON
T.cid = L.CID AND
T.CVID = R.OriginalCVID