对于唯一列值,请找到删除了重复项的多个不同值

时间:2018-02-07 19:18:25

标签: oracle

我认为标题可能令人困惑,所以我在这里解释一下。对于那个很抱歉。 在下面解释 -

Table A -
USERID 
1
2
3
4
5

Table B -
User ID     City
1           New York
1           New York
1           New Delhi
2           Boston
2           Dallas 
2           Boston
3           Las Vegas
4           Bombay
5           Hong Kong

所以我需要查询,这将导致用户ID和不同的城市值,没有重复项,并且有超过1个城市。

结果集 -

UserID   City
1        New York
1        New Delhi
2        Boston
2        Dallas

4 个答案:

答案 0 :(得分:1)

这是一种方法,使用分析函数(这样只需要处理一次数据):

with
  table_b ( user_id, city ) as (
    select 1, 'New York'  from dual union all
    select 1, 'New York'  from dual union all
    select 1, 'New Delhi' from dual union all
    select 2, 'Boston'    from dual union all
    select 2, 'Dallas'    from dual union all
    select 2, 'Boston'    from dual union all
    select 3, 'Las Vegas' from dual union all
    select 4, 'Bombay'    from dual union all
    select 4, 'Bombay'    from dual union all
    select 5, 'Hong Kong' from dual
  )
select user_id, city
from
       (
         select user_id, city,
                count(distinct city) over (partition by user_id) as cnt,
                row_number() over (partition by user_id, city order by null) as rn
         from   table_b
       )
where  cnt > 1 and rn = 1
;

   USER_ID CITY    
---------- ---------
         1 New Delhi
         1 New York 
         2 Boston   
         2 Dallas   

答案 1 :(得分:0)

尝试

Select 
    x.*
From (
    Select
        x.*,
        count() over(partition by x.userid) cnt
    From (
        Select distinct
            a.userid,
            b.city 
        From 
            tablea a
            inner join tableb b on b.userid = a.userid
    ) x
) x
Where
    x.cnt >= 2

答案 2 :(得分:0)

这个怎么样?

SQL> with test (user_id, city) as
  2    (select 1, 'new york' from dual union all
  3     select 1, 'new york' from dual union all
  4     select 1, 'new delhi' from dual union all
  5     select 2, 'boston' from dual union all
  6     select 2, 'dallas' from dual union all
  7     select 2, 'boston' from dual union all
  8     select 3, 'las vegas' from dual union all
  9     select 4, 'bombay' from dual union all
 10     select 5, 'hong kong' from dual
 11    )
 12  select distinct user_id, city
 13  from test
 14  where user_id in (select user_id
 15                    from test
 16                    group by user_id
 17                    having count(distinct city) > 1
 18                   );

   USER_ID CITY
---------- ---------
         1 new york
         1 new delhi
         2 boston
         2 dallas

SQL>

答案 3 :(得分:0)

以下作品:

 select distinct * from test t2
 where 
 exists (
    select 1 from test t1 
   where t1.UserID=t2.UserID
   having count(distinct t1.City) > 1
 )