我有以下查询来查找存在超过1次的所有条目。
SELECT p.Caption, COUNT(o.NodeID) as Count
FROM
NodesData p INNER JOIN
Interfaces o ON o.NodeID = p.NodeID
GROUP BY p.Caption, o.Caption
HAVING Count(o.NodeID) > '1'
查询工作正常。但是,我想在Select中添加其他数据。执行此操作时,它会中断查询,因为所有计数都是1.如何在允许查看其他数据的同时使查询仍然执行准确计数。例如,见下文。
SELECT p.Caption, o.Caption, COUNT(o.NodeID) as Count
FROM
NodesData p INNER JOIN
Interfaces o ON o.NodeID = p.NodeID
GROUP BY p.Caption, o.Caption
HAVING Count(o.NodeID) > '1'
答案 0 :(得分:1)
;WITH cte AS (
SELECT p.Caption, o.Caption as InterfaceCaption, COUNT(o.NodeId) OVER (PARTITION BY p.Caption) as NodeCount
FROM
NodesData p
INNER JOIN Interfaces o
ON o.NodeId = p.NodeId
)
SELECT *
FROM
cte
WHERE
NodeCount > 1
在公用表表达式(或派生表)中使用COUNT() OVER
窗口函数,然后添加您的where子句。否则,您必须获取第一个查询的结果并加入表格以检索所需的其他详细信息。
你也可以使用连接回原始表方法,但在我看来它更详细:
;WITH cte AS (
SELECT p.Caption, COUNT(o.NodeID) as Count
FROM
NodesData p INNER JOIN
Interfaces o ON o.NodeID = p.NodeID
GROUP BY p.Caption, o.Caption
HAVING Count(o.NodeID) > '1'
)
SELECT
*
FROM
cte c
INNER JOIN NodesData p
ON c.Caption = p.Caption
INNER JOIN Interfaces o
ON p.NodeId = o.NodeId
答案 1 :(得分:0)
你可能会得到一个,因为o.Caption在接口上的每一行都不同,你可以通过在其上执行MAX来欺骗o.Caption,如下所示: