unir múltiples expresiones de tabla comunes

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

preguntado el 22 de septiembre de 13 a las 08:09

¿Está utilizando SQL Server 2008 ? -

You can have multiple CTEs in a query, so just add them together. stackoverflow.com/questions/13134320/… -

2 Respuestas

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

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 or haz tu propia pregunta.