Thursday, January 18, 2018

ORACLE - How get already first/last row value from dataset (dense_rank)

Suppose this data:
select tl_nr, bel_nr, bew_dat, bew_art from factory.himtbw
where
tl_nr like 'S-442-700-0000' and
to_char( bew_dat, 'yyyymm' ) = '201503'

TL_NR                BEL_NR BEW_DAT  BE
-------------------- ------ -------- --
S-442-700-0000       108923 03.03.15 PP
S-442-700-0000       108924 03.03.15 PP
S-442-700-0000       391498 11.03.15 VY
S-442-700-0000       391498 11.03.15 PR
S-442-700-0000       384932 12.03.15 VV
S-442-700-0000       384936 12.03.15 VV
S-442-700-0000       394694 20.03.15 VV
S-442-700-0000       401817 26.03.15 VV

8 rows selected. 
When you need to get BEW_ART type for last date, you can use oracle analytical function dense_rank for it:
select min( bew_art ) keep ( dense_rank last order by ( bew_dat ) ),
min( bel_nr ) keep ( dense_rank last order by ( bew_dat ) ) from factory.himtbw
where
tl_nr like 'S-442-700-0000' and
to_char( bew_dat, 'yyyymm' ) = '201503'
Output:
MI MIN(BE
-- ------
VV 401817
How it works: You get BEW_ART/BEL_NR from data set, which is ordered by BEW_DAT -> and you use for data LAST row (when is there in this sorting one row only).

No comments:

Post a Comment