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

Oracle 对于唯一的列值,请查找多个删除重复项的不同值,oracle,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 Bom

我想标题可能会让人困惑,所以我会在这里解释。很抱歉。 下面解释一下-

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和不同的城市值,没有重复项,并且有多个城市

结果集-

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

这个怎么样

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>

这里有一种方法,使用分析函数,使数据只需处理一次:

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   
以下工作:

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

海报只想为那些至少有两个不同城市的用户ID返回行。你的解决方案不起作用,我错了。谢谢。这很有效,而且非常复杂。我为此写了一英里长的查询。虽然这只是一个示例,但实际上我正在处理大量数据,需要将更多的表连接在一起。但这是一条路要走。谢谢,帮了大忙。
 select distinct * from test t2
 where 
 exists (
    select 1 from test t1 
   where t1.UserID=t2.UserID
   having count(distinct t1.City) > 1
 )