将计数列添加到SQL查询

时间:2019-09-10 16:00:38

标签: sql sql-server

除了要有一个查询显示来自NodeGuid列匹配的两个表的列外,我还想向每行添加一列,该行包含此查询中包含当前行的table1.NodeGuid的总行数。

SELECT table1.NodeGuid
, table2.MarkerGuid mg
, --Need this column which contains a count of the total rows in this query that contain the current row's table1.NodeGuid
FROM table1
   , table2
WHERE table2.NodeGuid = table1.NodeGuid

谢谢。

1 个答案:

答案 0 :(得分:5)

您可以使用窗口功能。 。 。以及正确,明确,标准 JOIN语法:

SELECT table1.NodeGuid, table2.MarkerGuid mg,
       COUNT(*) OVER (PARTITION BY table1.NodeGuid) as cnt
FROM table1 JOIN
     table2
     ON table2.NodeGuid = table1.NodeGuid