sql query to find the duplicate records

2019-02-06 06:56发布

what is the sql query to find the duplicate records and display in descending, based on the highest count and the id display the records.

for example:

getting the count can be done with

select title, count(title) as cnt from kmovies group by title order by cnt desc

and the result will be like

title cnt

ravi   10
prabhu  9
srinu   6

now what is the query to get the result like below:

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

5条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-06 07:33

You can do it in a single query:

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
查看更多
Root(大扎)
3楼-- · 2019-02-06 07:33
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楼-- · 2019-02-06 07:39

This query uses the Group By and and Having clauses to allow you to select (locate and list out) for each duplicate record. The As clause is a convenience to refer to Quantity in the select and Order By clauses, but is not really part of getting you the duplicate rows.

Select
    Title,
    Count( Title ) As [Quantity]
   From
    Training
   Group By
    Title
   Having 
    Count( Title ) > 1
   Order By
    Quantity desc
查看更多
小情绪 Triste *
5楼-- · 2019-02-06 07:49

If your RDBMS supports the OVER clause...

SELECT
   title
FROM
    (
    select
       title, count(*) OVER (PARTITION BY title) as cnt
    from
      kmovies
    ) T
ORDER BY
   cnt DESC
查看更多
我命由我不由天
6楼-- · 2019-02-06 07:59

You can't do it as a simple single query, but this would do:

select title
from kmovies
where title in (
    select title
    from kmovies
    group by title
    order by cnt desc
    having count(title) > 1
)
查看更多
登录 后发表回答