1

第一个 SQL 查询(总内存)

SELECT 
Nodes.NodeID AS NodeID,  Nodes.TotalMemory AS TotalMemory, Nodes.Caption AS NodeName
 FROM 
(Nodes INNER JOIN Volumes ON (Nodes.NodeID = Volumes.NodeID))

第二个 SQL 查询(节点上的 CPU 数量)

SELECT N.Caption, COUNT(DISTINCT CPUIndex)

FROM CPUMultiLoad_Detail CPU WITH(NOLOCK)

JOIN Nodes N ON CPU.NodeID = N.NodeID

GROUP BY
N.Caption
Order By
N.Caption

我想加入第一个查询和第二个查询,所以我在同一个表中的节点上同时拥有总内存和 CPU 数量。我如何加入这两个查询?我们可以使用公共密钥Nodes.NodeID加入,但如何?

4

4 回答 4

3

在一般情况下,只需使用连接和 CTE

WITH PartOne AS
(
  SELECT N.NodeID, COUNT(DISTINCT CPU.Index) as [Count]
  FROM CPUMultiLoad_Detail CPU WITH(NOLOCK)
  JOIN Nodes N ON CPU.NodeID = N.NodeID
  GROUP BY N.Caption
)
SELECT Nodes.NodeID 
       Nodes.TotalMemory , 
       Nodes.Caption AS NodeName,
       PartOne.[Count]
FROM Nodes 
INNER JOIN Volumes ON Nodes.NodeID = Volumes.NodeID
JOIN PartOne ON PartOne.NodeID = Nodes.NodeID

这种特殊情况也可以在一个查询中完成,如下所示:

SELECT Nodes.NodeID 
       Nodes.TotalMemory , 
       Nodes.Caption AS NodeName,
       COUNT(DISTINCT CPU.Index) OVER (PARTITION BY Nodes.Caption ORDER BY Nodes.Caption) AS [Count]
FROM Nodes 
JOIN Volumes ON Nodes.NodeID = Volumes.NodeID
JOIN CPUMultiLoad_Detail CPU ON  CPU.NodeID = Nodes.NodeID
于 2013-10-28T17:25:17.310 回答
1

对于同样的情况,我使用了临时表

选择......从......进入#Temp1

选择......从......进入#Temp2

选择.....从#Temp1,#Temp2 WHERE #Temp1.NodeID = #Temp2.​​NodeID

记得像这样删除临时表:

删除表#Temp1 删除表#Temp2

于 2013-10-28T17:22:18.300 回答
0

SELECT t1.col2,t2.col3 FROM (SELECT NodeID col1,TotalMemory col2,Caption col3 FROM Nodes)t1 join
(SELECT NodeID col1,Caption col2,COUNT(DISTINCT CPUIndex) col3 FROM CPUMultiLoad_Detail CPU WITH(NOLOCK) GROUP BY Caption Order By Caption)t2 ON t1.col1=t2.col1
于 2013-10-28T17:35:21.500 回答
0

“With”有助于进行干净的查询:

    WITH CPUOnNodes AS (    
       SELECT N.NodeID, N.Caption, COUNT(DISTINCT CPUIndex)
       FROM CPUMultiLoad_Detail CPU WITH(NOLOCK)
       JOIN Nodes N ON CPU.NodeID = N.NodeID
       GROUP BY N.NodeID, N.Caption
       Order By N.Caption
    )
    SELECT N.NodeID, N.TotalMemory, N.Caption NodeName
    FROM Nodes N 
    INNER JOIN Volumes V ON N.NodeID = V.NodeID
    INNER JOIN CPUOnNodes C ON N.NodeID = C.NodeID
于 2013-10-28T17:22:18.257 回答