sql query to find the duplicate records

可紊 提交于 2019-11-29 12:12:57

问题


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

回答1:


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



回答2:


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



回答3:


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



回答4:


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



回答5:


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
)


来源:https://stackoverflow.com/questions/6779607/sql-query-to-find-the-duplicate-records

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!