20

我有两个查询,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命令来做到这一点?

谢谢

4

2 回答 2

27

试试这个查询,也许这就是你要找的。

;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
于 2013-09-22T07:58:47.150 回答
6
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......

于 2013-09-22T07:56:17.243 回答