분석함수 LAST_VALUE(), FIRST_VALUE() 질문 1 8 2,803

by 조신부리 [SQL Query] 분석함수 LAST_VALUE FIRST_VALUE [2018.04.25 14:41:52]


안녕하세요.

with t as
(
select 1 as id, 'txt1' as txt  from dual
union all select 2, '' from dual
union all select 3, 'txt3' from dual
union all select 4, '' from dual
union all select 5, '' from dual
union all select 6, 'txt6' from dual
union all select 7, '' from dual
union all select 8, '' from dual
)
select id
     , txt
     , first_value(txt) over(order by id desc) txt2
 from t
 order by id desc

가장큰 id의 txt값을 모든행에 표시함(txt가 null 이면 그이전값)==> 모든행에 txt6 로 반환함

by 우리집아찌 [2018.04.25 14:56:22]
with t as
(
select 1 as id, 'txt1' as txt  from dual
union all select 2, '' from dual
union all select 3, 'txt3' from dual
union all select 4, '' from dual
union all select 5, '' from dual
union all select 6, 'txt6' from dual
union all select 7, '' from dual
union all select 8, '' from dual
)
select id
     , txt
     , last_value(txt) ignore nulls over(order by id asc) txt2
 from t
 order by id desc 
 

 


by 조신부리 [2018.04.26 09:44:41]

빠른 답변 감사합니다.

업무에 적용하는데 문제는 없지만, 모든리스트에 tex6가 나와야 해서...양해바랍니다.


by 마농 [2018.04.25 16:41:27]
SELECT id
     , txt
     , MAX(txt) KEEP(DENSE_RANK LAST ORDER BY NVL2(txt, 2, 1), id) OVER() txt2
     , FIRST_VALUE(txt) OVER(ORDER BY NVL2(txt, 1, 2), id DESC) txt3
     , LAST_VALUE(txt) IGNORE NULLS OVER(ORDER BY id
       RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) txt4
  FROM t
 ORDER BY id DESC
;

 


by 조신부리 [2018.04.26 09:46:51]

감사합니다.

tibero 에서는 IGNORE NULLS 위치가 다르네요.

LAST_VALUE(txt IGNORE NULLS) OVER(ORDER BY id(RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) 

이렇게 해야 되네요...ㅎ


by 마농 [2018.04.26 09:59:17]

사용하신 OVER 구문에 정렬 구문이 빠져 있네요.
이미 정렬되어 있는 상태라면 맞는 결과가 나올 수도 있겠지만.
정렬되어 있지 않은 경우에도 올바른 결과가 나올지 의문이네요?
위와 같이 사용하려면 인라인뷰 안에서 미리 정렬을 해줘야 하지 않을까? 생각되네요.


by 조신부리 [2018.04.26 10:22:28]

네...over 안에 정렬구문 들어가야하는거구요.

쿼리를 감상하면 슬며시 미소가 지어집니다.

멋진쿼리 감사합니다.


by 마농 [2018.04.26 10:24:28]

단순하게 OVER 안에 정렬구문만 넣어서는 원하는 결과가 나오지 않습니다.
그래서 RANGE 구문을 추가한 것입니다.


by 마농 [2018.04.26 14:29:00]

IGNORE NULLS 구문이 처음 소개되었을 때(10G ?)는 괄호 안에 사용 했었는데요.
11G 부터는 괄호 밖으로 뺐네요. 이게 표준인 듯 합니다.
물론 과거 버전 호환을 위해 괄호 안에 써도 동작 됩니다.

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