unir múltiples expresiones de tabla comunes
Frecuentes
Visto 59,449 veces
22
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
y Query2.TagNo
how can i use join these two querys, is it possible to do that with With
¿Mando?
Gracias
2 Respuestas
29
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
respondido 18 nov., 16:23
it brings back just a part of result - nnmmss
Try to use the FULL JOIN instead of INNER JOIN in the last SELECT statement - Aleksandr Fedorenko
7
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
join cte2 on cte1.TagNo = cte2.TagNo
where cte.rn = 1 and cte2.rn = 1;
I don't know if the condition cte.rn = 1 and cte2.rn = 1
is what you want. Maybe you just want it on one of the CTEs, maybe on both, maybe you actually want an outer join with cte2.rn = 1
in the join condition...
Respondido el 22 de Septiembre de 13 a las 10:09
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas sql sql-server-2008 tsql common-table-expression or haz tu propia pregunta.
¿Está utilizando
SQL Server 2008
? - Ashish GaurYou can have multiple CTEs in a query, so just add them together. stackoverflow.com/questions/13134320/… - ta.speot.is