如何获得总重复行数?

时间:2018-06-06 17:53:03

标签: sql database group-by

假设我有一个表“员工

|  id  | Name  |
----------------
|   1  |  AAA  |
----------------
|   1  |  AAA  |
----------------
|   2  |   BBB |
----------------
|   2  |  BBB  |
----------------
|   2  |  BBB  |
----------------

我想计算重复的行,所以结果将是5(总共2和3)

我尝试的查询是: -

select count(id)
from Employee
group by id
having count(id) > 1

按预期输出: -

  | 2 |
   -----
   | 3 |
   -----

我怎样才能达到总数,我的意思是5

1 个答案:

答案 0 :(得分:1)

最简单的方法是将其包装在另一个查询中:

SELECT SUM(counts) 
FROM (
select count(id) counts
from Employee
group by id
having count(id) > 1) inner_query

编辑:

更复杂的方法是使用group bysum window function& distinct在同一语句中避免内部子查询。

SELECT DISTINCT SUM(COUNT(id)) OVER () count_duplicates
FROM Employee
GROUP BY id
HAVING COUNT(id) > 1