0

我有一个名为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 
4

3 回答 3

1

作为 xQbert 答案的替代方案,您也可以使用分析函数在不连接的情况下执行此操作:

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()为您提供每个的第一个 ID(即最小数字)name;然后,外部查询会排除行与自身匹配的情况 - 因此仅列出重复项,并且不显示每个项的第一次出现。

于 2013-02-25T14:21:35.253 回答
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/

于 2013-02-25T13:57:52.227 回答
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
于 2013-02-25T14:10:07.140 回答