Duplication

如何在不使用 GROUP BY 或 COUNT 的情況下執行顯示同一表中具有兩次以上的任何行的查詢

  • April 3, 2018

我想在沒有 GROUP BY 或 COUNT 語句的情況下選擇出現在同一個表中的所有相同項目兩次。如何編寫查詢?

例如,如果表是:

City
---------
New York
Los Angeles
London
Washington
London
Peking
London
San Fransisco
New York
Tokyo
Dubai

結果集應該是這樣的:

City
---------
New York
London

(因為 ‘New York’ 出現了 3 次,而 ‘London’ 在原始表中出現了兩次)

with data as
(
select 'New York' as city from dual union all
select 'Los Angeles' from dual union all
select 'London' from dual union all
select 'Washington' from dual union all
select 'London' from dual union all
select 'Peking' from dual union all
select 'London' from dual union all
select 'San Fransisco' from dual union all
select 'New York' from dual union all
select 'Tokyo' from dual union all
select 'Dubai' from dual
)
select
 distinct city
from
(
 select
   city,
   row_number() over (partition by city order by null) as rn
 from
   data
) 
where
 rn > 1
;

CITY
-------------
London
New York

沒有 GROUP BY,沒有 COUNT。

但是我們有 DISTINCT、ROW_NUMBER()、PARTITION BY、ORDER BY。

它比它更簡單/更好嗎?

with data as
(
select 'New York' as city from dual union all
select 'Los Angeles' from dual union all
select 'London' from dual union all
select 'Washington' from dual union all
select 'London' from dual union all
select 'Peking' from dual union all
select 'London' from dual union all
select 'San Fransisco' from dual union all
select 'New York' from dual union all
select 'Tokyo' from dual union all
select 'Dubai' from dual
)
select
 city
from
 data
group by
 city
having
 count(*) > 1
;

不,我猜。

如果您在該表中有一個主鍵(或其他一些唯一列),例如,id您可以使用:

select distinct c1.city
from cities c1
where exists (select *
             from cities c2
             where c1.city = c2.city
             and c1.id <> c2.id);

如果您沒有這樣的列並且您使用的是 Postgres,則可以使用內置的ctid。對於 Oracle,您可以使用rowid.


如果您沒有唯一的列並且不使用 Postgres 或 Oracle,那麼您應該真正使用,count()因為這是最有效的解決方案。group by``having

引用自:https://dba.stackexchange.com/questions/202899