Re: Help on query -
09-03-2010
, 04:02 PM
Even if you showed the data with ORDER BY some columns, many of
DBMS(including DB2) don't assume the order.
Order of rows are supposed only in queries by specifying ORDER BY
clause explicitly.
Anyhow, if supposing order of col2 and rows with contnued same col1 as
one set,
then this may be an solution:
------------------------------ Commands Entered
------------------------------
WITH
test_data(Col1 , Col2) AS (
VALUES
('B' , 0 )
, ('B' , 0.5)
, ('A' , 1 )
, ('A' , 1.5)
, ('B' , 2 )
, ('A' , 3 )
, ('A' , 4 )
, ('B' , 5 )
, ('B' , 6 )
, ('C' , 7 )
, ('A' , 8 )
)
SELECT col1 , col2
FROM (SELECT col1 , col2
, MAX(col1)
OVER(ORDER BY col2
ROWS BETWEEN 1 PRECEDING
AND 1 PRECEDING)
AS pre_col1
FROM test_data
) s
WHERE col1 = 'B'
AND
( pre_col1 <> 'B'
OR pre_col1 IS NULL
)
ORDER BY
col2 DESC
FETCH FIRST 1 ROW ONLY
;
------------------------------------------------------------------------------
COL1 COL2
---- --------------
B 5.0
1 record(s) selected.
or if you are using DB2 9.5 or later for LUW:
------------------------------ Commands Entered
------------------------------
WITH
test_data(Col1 , Col2) AS (
VALUES
('B' , 0 )
, ('B' , 0.5)
, ('A' , 1 )
, ('A' , 1.5)
, ('B' , 2 )
, ('A' , 3 )
, ('A' , 4 )
, ('B' , 5 )
, ('B' , 6 )
, ('C' , 7 )
, ('A' , 8 )
)
SELECT col1 , col2
FROM (SELECT col1 , col2
, LAG(col1 , 1 , ' ')
OVER(ORDER BY col2)
AS pre_col1
FROM test_data
) s
WHERE col1 = 'B'
AND pre_col1 <> 'B'
ORDER BY
col2 DESC
FETCH FIRST 1 ROW ONLY
;
------------------------------------------------------------------------------
COL1 COL2
---- --------------
B 5.0
1 record(s) selected. |