Вопрос

I am trying to combine my query into a join to bring back some records.

Here is the first part of my query, this does exactly what I want and returns the latest record from this result set as each record is linked to the other by an fkSDSID as show below, the first one does not have an id as its the first one and there are no previous records.

pkSDSID   fkSDSID
 50605     NULL
 88377     50605
 90602     88377
 90616     90602

This query returns 90616 from the results.

DECLARE @LatestSDS INT

with tree as (
   SELECT pkSDSID, fkSDSID
   FROM tblSDS
   WHERE pkSDSID = 50605

   UNION ALL

   SELECT t1.pkSDSID, t1.fkSDSID
   FROM tblSDS t1
   JOIN tree p ON p.pkSDSID = t1.fkSDSID
)

SELECT TOP 1 @LatestSDS = pkSDSID FROM tree ORDER BY pkSDSID DESC

SELECT @LatestSDS

This is fine if I have one record I want to find but what I'm now stuck on his how to do this for multiple records.

I was wondering if I could inner join this somehow using it as a sub query of my main query but I cant seem to find a way to get it to work.

What I would like is to replace the hard coded pkSDSID in the first where clause like above which is 50605 and instead use a column or a number of records and get the LastestSDS for each record.

An example being this

I have two records say 50605 and 45670.

They both have newer records like so in the table

pkSDSID   fkSDSID
 50605     NULL
 88377     50605
 90602     88377
 90616     90602

pkSDSID   fkSDSID
 45670     NULL
 50123     45670
 51234     50123
 60125     51234

So for each of these records I need to use my code above to get the latest record which would be 90616 and 60125 respectively.

Then display just these new records in a list.

I hope this makes sense I'm not all that great with SQL and I just don't know where to go from here.

Is this actually possible?

Thanks Dan

Это было полезно?

Решение

Edit, after Q update

DECLARE @t TABLE (pkSDSID int NOT NULL, fkSDSID int NULL);
INSERT @t VALUES
(50605, NULL),
(88377, 50605),
(90602, 88377),
(90616, 90602),
(45670, NULL),
(50123, 45670),
(51234, 50123),
(60125, 51234);

with tree as (
   SELECT S.pkSDSID, S.fkSDSID, 0 AS TreeLevel, S.pkSDSID AS TreeTop
   FROM @t S
   WHERE S.pkSDSID IN (50605, 45670)

   UNION ALL

   SELECT t1.pkSDSID, t1.fkSDSID, TreeLevel +1, p.TreeTop
   FROM @t t1
   JOIN tree p ON p.pkSDSID = t1.fkSDSID
)
, Filter AS
(
SELECT
     pkSDSID,
     ROW_NUMBER() OVER (PARTITION BY TreeTop ORDER BY TreeLevel DESC) AS rn
 FROM tree
)
SELECT pkSDSID FROM Filter WHERE rn = 1
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top