使用WITH子句的结果执行JOIN

问题描述 投票:0回答:1

我有一个已经使用一个联接的查询,将其称为query1。我想将query1加入WITH子句的结果中。我不知道如何合并两个数据集。

查询1:

SELECT 
    p.NetObjectID, 
n.Caption, n.ObjectSubType
FROM Pollers p
  LEFT JOIN NodesData n 
    ON n.NodeID = p.NetObjectID

下一个查询是WITH子句。我不知道如何在不使用WITH的情况下获得结果,因为我需要执行this post中概述的操作。

查询2:

WITH ranked_DateStamp AS 
        (
        SELECT c.NodeID, c.DateTime, ROW_NUMBER() OVER (PARTITION BY NodeID ORDER BY DateTime DESC) AS rn
        FROM CPULoad AS c
        )
SELECT * FROM ranked_DateStamp WHERE rn = 1;

我以为我可以将rank_DateStamp加入JOIN_DateStamp.NodeID = p.NodeID,但不允许这样做。

sql sql-server
1个回答
0
投票

您不需要真正在这里需要with子句,可以使用子查询。我只是这样说:

SELECT 
    p.NetObjectID, 
    n.Caption, 
    n.ObjectSubType,
    c.DateTime
FROM Pollers p
LEFT JOIN NodesData n ON n.NodeID = p.NetObjectID
LEFT JOIN (
    SELECT 
        c.NodeID, 
        c.DateTime, 
        ROW_NUMBER() OVER (PARTITION BY NodeID ORDER BY DateTime DESC) AS rn
    FROM CPULoad AS c
) c ON c.rn = 1 and c.NodeID = p.NetObjectID

但是,如果要使用公用表表达式,则看起来像:

WITH ranked_DateStamp AS (
    SELECT 
        c.NodeID, 
        c.DateTime, 
        ROW_NUMBER() OVER (PARTITION BY NodeID ORDER BY DateTime DESC) AS rn
    FROM CPULoad AS c
)
SELECT 
    p.NetObjectID, 
    n.Caption, 
    n.ObjectSubType,
    c.DateTime
FROM Pollers p
LEFT JOIN NodesData n ON n.NodeID = p.NetObjectID
LEFT JOIN ranked_DateStamp c ON c.rn = 1 and c.NodeID = p.NetObjectID
热门问题
推荐问题
最新问题