programing

Postgres의 DISTINCT ON에 해당하는 Oracle?

jooyons 2023. 6. 14. 21:51
반응형

Postgres의 DISTINCT ON에 해당하는 Oracle?

postgres에서 그룹의 첫 번째 값을 쿼리할 수 있습니다.DISTINCT ONOracle에서 이를 달성하는 방법은 무엇입니까?

Postgres 매뉴얼에서:

SELECT DISTINCT ON(표현식 [, ...])은 지정된 표현식이 동일하다고 평가되는 각 행 집합의 첫 번째 행만 유지합니다.DISTINCT ON 표현식은 ORDER BY와 동일한 규칙을 사용하여 해석됩니다(위 참조).원하는 행이 먼저 나타나도록 ORDER BY를 사용하지 않는 한 각 집합의 "첫 번째 행"을 예측할 수 없습니다.

예를 들어, 주어진 테이블의 경우:

 col1 | col2 
------+------
 A    | AB
 A    | AD
 A    | BC
 B    | AN
 B    | BA
 C    | AC
 C    | CC

오름차순 정렬:

> select distinct on(col1) col1, col2 from tmp order by col1, col2 asc;
 col1 | col2 
------+------
 A    | AB
 B    | AN
 C    | AC

내림차순 정렬:

> select distinct on(col1) col1, col2 from tmp order by col1, col2 desc;
 col1 | col2 
------+------
 A    | BC
 B    | BA
 C    | CC

함수를 사용하거나 또는 함수 중 하나를 사용하여 Oracle에서 동일한 효과를 복제할 수 있습니다.

두 변형 모두 Postgres에서도 작동합니다.

first_value()

select distinct col1, 
first_value(col2) over (partition by col1 order by col2 asc)
from tmp

first_value파티션에 대한 첫 번째 값을 제공하지만 각 행에 대해 이 값을 반복하므로 이 값을 와 함께 사용해야 합니다.distinct각 파티션에 대해 단일 행을 가져옵니다.

row_number()/rank()

select col1, col2 from (
  select col1, col2, 
  row_number() over (partition by col1 order by col2 asc) as rownumber 
  from tmp
) foo
where rownumber = 1

교체row_number()와 함께rank()이 예제에서는 동일한 결과를 산출합니다.

이 변형 모델의 특징은 단순히 변경함으로써 주어진 파티션의 첫 번째 N개 행(예: "마지막 3개 업데이트")을 가져오는 데 사용할 수 있다는 것입니다.rownumber = 1로.rownumber <= N.

필드가 두 개 이상인 경우 하위 쿼리로 비어베이 답변을 사용합니다(DESC 순서 참고).

select col1,col2, col3,col4 from tmp where col2 in
(
select distinct 
first_value(col2) over (partition by col1 order by col2 DESC) as col2
from  tmp
--WHERE you decide conditions
)

언급URL : https://stackoverflow.com/questions/10515391/oracle-equivalent-of-postgres-distinct-on

반응형