Select max date, then max time

非 Y 不嫁゛ 提交于 2019-12-08 05:57:28

问题


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


回答1:


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



回答2:


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;



回答3:


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  



回答4:


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)


来源:https://stackoverflow.com/questions/14255305/select-max-date-then-max-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!