我有一个名为unique_table
的表,其数据如下:
ID NAME
1 venkat
2 subash
3 venkat
4 subash
5 venkat
6 subash
我想查询上面的表格并获得如下的输出:
ID NAME MATCHED_ID
3 venkat 1
4 subash 2
5 venkat 1
6 subash 2
答案 0 :(得分:1)
SELECT YourColumn, COUNT(*) MatchedCount
FROM YourTable
GROUP BY YourColumn
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
http://blog.sqlauthority.com/2007/07/11/sql-server-count-duplicate-records-rows/
答案 1 :(得分:1)
Select T2.ID, T2.name, min(T1.ID) as matched_ID
FROM D t1
INNER JOIN D t2 on t1.ID < T2.ID
and T1.name = T2.name
Group by T2.name, T2.ID
order by ID
create table D as (
Select 1 as ID ,'venkat' as name from dual UNION
SELECT 2,'subash' from dual UNION
SELECT 3,'venkat' from dual UNION
SELECT 4,'subash' from dual UNION
SELECT 5 ,'venkat' from dual UNION
SELECT 6,'subash' from dual)
结果
ID Name Matched ID
3 venkat 1
4 subash 2
5 venkat 1
6 subash 2
答案 2 :(得分:1)
作为xQbert答案的替代方法,您也可以使用analytic functions在没有连接的情况下执行此操作:
select id, name, matched_id
from (
select id,
name,
first_value(id) over (partition by name order by id) as matched_id
from unique_table
)
where id != matched_id
order by id;
ID NAME MATCHED_ID
---------- ------ ----------
3 venkat 1
4 subash 2
5 venkat 1
6 subash 2
在内部查询中,first_value()
为您提供每个name
的第一个ID(即最低编号);外部查询然后排除行匹配的情况 - 因此只列出重复项,并且不显示每个行的第一次出现。