I have two Query, Query1:
with cte as (
select
dbo.Cable.*,
row_number() over(partition by dbo.Cable.TagNo order by dbo.Cable.CableRevision desc) as rn
from dbo.Cable
where (dbo.Cable.CableRevision = @CoreRevision )
)
select *
from cte
where rn = 1
and also Query2
with cte as (
select
dbo.Cable.TagNo,dbo.Core.*,
row_number() over(partition by dbo.Core.CoreNo order by dbo.Core.CoreRevision desc) as rn
from dbo.Core INNER JOIN
dbo.Cable ON dbo.Cable.Id = dbo.Core.CableId
where (dbo.Core.CoreRevision <= @CoreRevision )
)
select *
from cte
where rn = 1
these two query are related by Query1.TagNo
and Query2.TagNo
how can i use join these two querys, is it possible to do that with With
Command?
Thank you
A straightforward question deserves a straightforward answer: yes, you can. Now that you know how to use multiple CTEs, writing a CTE that references another CTE is just a variation of what you've learned.
You can create recursive CTE or use a reference of a CTE to another CTE. However there is a slight differences compared with other databases - The referenced CTE must be present after the referencing CTE.
Try this query, perhaps this is what you are looking for.
;WITH cte AS
(SELECT dbo.Cable.*,
row_number() over(partition by dbo.Cable.TagNo order by dbo.Cable.CableRevision desc) as rn
FROM dbo.Cable
WHERE dbo.Cable.CableRevision = @CoreRevision
), cte2 AS
(SELECT dbo.Cable.TagNo, dbo.Core.*,
row_number() over(partition by dbo.Core.CoreNo order by dbo.Core.CoreRevision desc) as rn
FROM dbo.Core INNER JOIN dbo.Cable ON dbo.Cable.Id = dbo.Core.CableId
WHERE dbo.Core.CoreRevision <= @CoreRevision
)
SELECT *
FROM cte c FULL JOIN cte2 c2 ON c.TagNo = c2.TagNo
WHERE c.rn = 1 OR c2.rn = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With