간단한 쿼리인데 이해가 되지 않습니다. 0 1 6,808

by 빈츠 [Oracle 기초] [2025.02.10 14:17:36]


<원본> 서브퀴리도 같은 이력 테이블 사용

***** 이력은 변경일련번호 컬럼을 단일 pk로 사용

select 변경일련번호

from 이력

where 변경일련번호 in ( 

   select max(변경일련번호)

   from 이력

   where type in ('a','b')

   group by 부서)

and type = 'b';

 

 

 

<변경> 하였더니 결과가 다름

select max(변경일련번호)

from 이력

and type = 'b'

group by 부서;

 

pk 조건에 의해 될 것 같은데 같지 않네요..

아래 집합이 원본을 모두 포함하고도 조금 더 row 가 많습니다

by 우주민 [2025.02.10 14:48:28]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
with 이력 as (
  select '부서1' as 부서, 'a' as type, 1 as 변경일련번호 union all
  select '부서1' as 부서, 'b' as type, 2 as 변경일련번호 union all
  select '부서2' as 부서, 'a' as type, 4 as 변경일련번호 union all
  select '부서2' as 부서, 'b' as type, 3 as 변경일련번호
)
select 변경일련번호
from 이력
where 변경일련번호 in (
   select max(변경일련번호)
   from 이력
   where type in ('a','b')
   group by 부서)
and type = 'b';
1
2
3
4
5
6
7
8
9
10
with 이력 as (
  select '부서1' as 부서, 'a' as type, 1 as 변경일련번호 union all
  select '부서1' as 부서, 'b' as type, 2 as 변경일련번호 union all
  select '부서2' as 부서, 'a' as type, 4 as 변경일련번호 union all
  select '부서2' as 부서, 'b' as type, 3 as 변경일련번호
)
select max(변경일련번호)
from 이력
where type = 'b'
group by 부서;

동일한 부서 안에서 변경일련번호의 max 값이 a type 인 데이터가 된다면 결과가 달라지게 됩니다.

(예시로 만든 쿼리의 '부서2' 항목) 

댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입