连接多个公用表表达式

时间:2013-09-22 07:08:51

标签: sql sql-server-2008 tsql common-table-expression

我有两个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

以及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

这两个查询与Query1.TagNoQuery2.TagNo相关联 我如何使用加入这两个查询,是否可以使用With命令执行此操作?

谢谢

2 个答案:

答案 0 :(得分:17)

尝试此查询,也许这就是您要找的内容。

;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

答案 1 :(得分:5)

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;

我不知道条件cte.rn = 1 and cte2.rn = 1是否符合您的要求。也许你只想在其中一个CTE上,也许在两者上,也许你真的想要在连接条件下使用cte2.rn = 1进行外连接......