sql查询查找重复记录

时间:2011-07-21 16:38:06

标签: sql duplicates

什么是sql查询,以查找重复记录并以降序显示,基于最高计数和id显示记录。

例如:

可以使用

完成计数
select title, count(title) as cnt from kmovies group by title order by cnt desc

,结果就像

title cnt

ravi   10
prabhu  9
srinu   6

现在获取结果的查询是什么,如下所示:

ravi
ravi
ravi
...10 times
prabhu
prabhu..9 times
srinu
srinu...6 times

5 个答案:

答案 0 :(得分:16)

如果您的RDBMS支持OVER子句......

SELECT
   title
FROM
    (
    select
       title, count(*) OVER (PARTITION BY title) as cnt
    from
      kmovies
    ) T
ORDER BY
   cnt DESC

答案 1 :(得分:6)

您可以在一个查询中执行此操作:

Select t.Id, t.title, z.dupCount
From yourtable T
Join
   (select title, Count (*) dupCount
    from yourtable 
    group By title
    Having Count(*) > 1) z
   On z.title = t.Title
order By dupCount Desc

答案 2 :(得分:5)

此查询使用Group ByHaving子句允许您为每个重复记录选择(定位和列出)。 As子句可以方便地引用Quantityselect子句中的Order By,但实际上并不是获取重复行的一部分。

Select
    Title,
    Count( Title ) As [Quantity]
   From
    Training
   Group By
    Title
   Having 
    Count( Title ) > 1
   Order By
    Quantity desc

答案 3 :(得分:1)

select distinct title, (
               select count(title) 
               from kmovies as sub 
               where sub.title=kmovies.title) as cnt 
from kmovies 
group by title 
order by cnt desc

答案 4 :(得分:0)

您不能将其作为简单的单个查询来执行,但这样做:

select title
from kmovies
where title in (
    select title
    from kmovies
    group by title
    order by cnt desc
    having count(title) > 1
)