WITH A AS
(
SELECT ’20090901’ DT , 10 CNT, ’1’ CD FROM DUAL UNION ALL
SELECT ’20090901’ DT , 30 CNT, ’2’ CD FROM DUAL UNION ALL
SELECT ’20090901’ DT , 10 CNT, ’1’ CD FROM DUAL UNION ALL
SELECT ’20090902’ DT , 10 CNT, ’1’ CD FROM DUAL
)
SELECT DT
, TT
FROM ( SELECT DT
, SUM( CASE WHEN CD = 2 THEN -CNT ELSE CNT END ) OVER( ORDER BY ROWNUM ) TT
, ROW_NUMBER() OVER( PARTITION BY DT ORDER BY ROWNUM DESC ) RN
FROM A
)
WHERE RN = 1