sql – 加入多个常用表表达式

前端之家收集整理的这篇文章主要介绍了sql – 加入多个常用表表达式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个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.TagNo和Query2.TagNo相关
我如何使用连接这两个查询,是否可以使用命令?

谢谢

解决方法

尝试这个查询,也许这是你正在寻找.
;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,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
原文链接:https://www.f2er.com/mssql/81367.html

猜你在找的MsSQL相关文章