SELECT COUNT(*)DISTINCT - 查找表中任何重复组的总次数

时间:2014-04-25 12:04:05

标签: sql sql-server

使用MS-SQL server 2008 r2我有一个表,我正在尝试计算重复组的数量:

id adId
1  a
2  a
3  b
4  c
5  c
6  c

我想在列adId中找到重复的记录总数。我想要的结果是2(因为a和c都被复制了)

这些不起作用,因为它们计算重复的行而不是重复的组

SELECT COUNT(*) AS TotalRecords 
FROM (SELECT DISTINCT adId FROM oc_cal_sc) 
HAVING COUNT(adId) > 1

SELECT COUNT(DISTINCT (adId)) AS TotalRecords 
FROM oc_cal_sc 
HAVING COUNT(adId) > 1

SELECT SUM(temp_1.adId) as TotalRecords 
FROM 
    (SELECT adId, count(1) AS count_1 
    FROM oc_cal_sc GROUP BY adId HAVING adId >1) 
as temp_1

关于如何解决这个问题的任何想法,因为我有点超出我的深度?

4 个答案:

答案 0 :(得分:2)

获取具有重复记录的记录:

SELECT adId,COUNT(adId) AS TotalRecords 
FROM oc_cal_sc
GROUP BY adId
HAVING COUNT(adId) > 1

根据您给出的示例,结果将是:

adId    TotalRecords
a       2
c       3

修改

获取具有重复项的记录数

SELECT COUNT(*) as TotDuplicates
FROM
(SELECT adId,COUNT(adId) AS TotalRecords 
    FROM oc_cal_sc
    GROUP BY adId
    HAVING COUNT(adId) > 1) T

结果将是:

TotDuplicates
2

答案 1 :(得分:2)

SELECT
  COUNT(1) TotalRecords
FROM (
  SELECT
    adId,
    COUNT(1)
  FROM oc_cal_sc
  GROUP BY adId
  HAVING COUNT(1) > 1
) x

答案 2 :(得分:2)

您可以将查询用作内部查询,并获取外部查询中的总计数:

select count(inner_count) AS TotalRecords from (
    select count(adId) AS inner_count
    from oc_cal_sc
    group by adId
    having count(adId) > 1
) x

答案 3 :(得分:2)

快速而肮脏的方式:

SELECT COUNT(*) AS NumberOfGroups 
FROM (
   SELECT aid FROM oc_cal_sc
   GROUP BY aid
   HAVING COUNT(aid) > 1
) T