我想计算接口的数量,然后编写这个代码,从两个表节点和接口中计算它们。这段代码有效,但我想知道这个代码的任何其他方式或优化?计算它们的最佳方式是什么?
SELECT
q1.NodeName,
q1.Nup as up,
q2.ndown as down
FROM (
SELECT
Nodes.NodeID AS NodeID,
Interfaces.NodeID AS InterfaceID,
Nodes.Caption AS NodeName,
Interfaces.Status as Status,
Count(Nodes.Caption) as Nup
FROM
Nodes INNER JOIN Interfaces ON (Nodes.NodeID = Interfaces.NodeID)
WHERE
(
(
(Interfaces.Status = '2'))
)
GROUP BY Nodes.NodeID, Nodes.Caption, Interfaces.Status, Interfaces.NodeID
) AS q1
INNER JOIN (
SELECT
Interfaces.NodeID AS InterfaceID,
Nodes.Caption AS NodeName,
Interfaces.Status as Status,
Count(Nodes.Caption) as ndown
FROM
Nodes INNER JOIN Interfaces ON (Nodes.NodeID = Interfaces.NodeID)
WHERE
(
(
(Interfaces.Status = '1'))
)
GROUP BY Nodes.NodeID, Nodes.Caption, Interfaces.Status, Interfaces.NodeID
) AS q2
ON (q1.NodeID = q2.InterfaceID)
order by down Desc
答案 0 :(得分:4)
您可以合并查询:
SELECT
Nodes.Caption AS NodeName,
Count(
CASE WHEN Interfaces.Status = '2'
THEN 1
ELSE NULL
END) as up,
Count(
CASE WHEN Interfaces.Status = '1'
THEN 1
ELSE NULL
END) as down
FROM Nodes
INNER JOIN Interfaces ON (Nodes.NodeID = Interfaces.NodeID)
WHERE Interfaces.Status IN('1', '2')
GROUP BY Nodes.NodeID, Nodes.Caption
order by 3 Desc
注意:在原始查询中,如果某个界面始终处于启用状态或始终处于关闭状态,则由于您使用的是INNER JOIN
,因此它不会显示在结果集中。
答案 1 :(得分:0)
我会简化接口上的内部查询,因为这是WHERE的完整基础,在结果集完成之前不需要加入节点,然后在单个节点完成后加入节点。
SELECT
Nodes.NodeName,
Q1.CountUp as Up,
Q1.CountDown as Down
FROM
( SELECT
Interfaces.NodeID AS InterfaceID,
SUM( CASE WHEN Interfaces.Status = '1' then 1 else 0 end ) as CountUp,
SUM( CASE WHEN Interfaces.Status = '2' then 1 else 0 end ) as CountDown
FROM
Interfaces
WHERE
Interfaces.Status IN ('1','2')
GROUP BY
1 ) AS q1
INNER JOIN Nodes
ON q1.NodeID = Nodes.NodeID
order by
3 desc