Digital God
Digital God

Reputation: 481

Select max date, then max time

I've table with currency rates:

T_RATE_ID  T_INPUTDATE  T_INPUTTIME  T_SINCEDATE
1          27.12.2012   22:41:01     28.12.2012
1          27.12.2012   23:45:21     28.12.2012
1          28.12.2012   21:23:11     29.12.2012
1          28.12.2012   21:40:01     29.12.2012
1          29.12.2012   22:33:49     30.12.2012
1          29.12.2012   23:47:19     30.12.2012

How to select max date and then max time for this date?

Simple SELECT MAX(t_sincedate), MAX(t_inputdate), MAX(t_inputtime) returns max time in all records (23:47:19)

I want get following results:

1  27.12.2012  23:45:21  28.12.2012
1  28.12.2012  21:40:01  29.12.2012
1  29.12.2012  23:47:19  30.12.2012

UPD: I have a date for wich i search rate. If there is no rate for this date, i take the nearest date.

So in where clause i've where t_sincedate <= sysdate

Upvotes: 1

Views: 11967

Answers (4)

knagaev
knagaev

Reputation: 2967

Probably I didn't catch the meaning of the question but I try.

select * 
from t 
where (t_inputdate, t_inputtime) in 
  (select t_inputdate, MAX(t_inputtime) from t group by t_inputdate)

Upvotes: 0

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Try this:

SELECT T_RATE_ID, T_INPUTDATE, T_INPUTTIME, T_SINCEDATE
FROM
   (SELECT 
       *, ROW_NUMBER() OVER (PARTITION BY T_SINCEDATE ORDER BY T_INPUTDATE DESC, T_INPUTTIME DESC) rn
     FROM YourTable
     WHERE T_SINCEDATE<= sysdate) T
WHERE rn = 1

Upvotes: 1

Ilion
Ilion

Reputation: 6882

Based on the results you provide you don't actually want the max date but the distinct dates with max times.

SELECT 
  T_RATE_ID,
  t_sincedate, 
  MAX(t_inputdate), 
  MAX(t_inputtime) 
FROM 
  <TABLE NAME> 
where t_sincedate <= sysdate
GROUP BY
  T_RATE_ID, t_sincedate
ORDER BY
  T_RATE_ID, t_sincedate;

Upvotes: 1

valex
valex

Reputation: 24144

SQLFiddle demo

select * from
(
select t.*,
       ROW_NUMBER() 
       OVER (partition by T_SINCEDATE 
             ORDER BY T_INPUTDATE DESC,T_INPUTTIME DESC) rn
from t
) t1 where rn=1  

Upvotes: 0

Related Questions