如何从DateTime获取一天

时间:2013-04-03 12:40:38

标签: sql oracle

假设我有以下Oracle表,我想要the last (aka max) entry by aGroup and day where the timepart of dateTime in less than 00:00:15(日期应该被提取为dateTime的日期部分)

它的SQL查询是什么(我不知道如何从dateTime中提取日期)?

              dateTime aGroup
2011-01-01 00:00:12      a
2011-01-01 00:00:31      a
2012-01-01 00:00:09      a
2012-01-01 00:00:03      a
2011-01-01 00:00:06      b
2011-01-01 00:00:14      b
2011-01-01 00:00:16      b
2012-01-01 00:00:16      b
2012-01-01 00:00:11      b

这是我希望的结果

              dateTime aGroup
2011-01-01 00:00:12      a
2012-01-01 00:00:09      a
2011-01-01 00:00:14      b
2012-01-01 00:00:11      b

4 个答案:

答案 0 :(得分:1)

考虑类似于此的查询:

SELECT 
  MAX(DateTime), 
  aGroup
FROM 
  tablename
WHERE 
  TIME_TO_SEC(TIME(DateTime)) < 15
GROUP BY 
  DATE(DateTime), 
  aGroup

这将为每个aGroup提供每天最长的时间(少于00:00:15)。

编辑:已更新为使用TIME_TO_SEC进行oracle

答案 1 :(得分:1)

TRUNC function非常便于提取日期:

SELECT dateTime, aGroup
FROM
(
    SELECT dateTime
          , aGroup
          , RANK() OVER (PARTITION BY aGroup, TRUNC(dateTime, 'DDD') ORDER BY dateTime DESC) as Rank
    FROM table
    WHERE (dateTime - TRUNC(dateTime, 'DDD')) * 24 * 3600 < 15
)
WHERE Rank = 1

该行

 WHERE (dateTime - TRUNC(dateTime, 'DDD')) * 24 * 3600 < 15

计算当前日期与当天开始之间的天数差异 乘以24和3600得到秒数,如果低于15则过滤。

答案 2 :(得分:1)

这是我尝试使用to_char

SELECT AGROUP, MAX(DATETIME) FROM MYTABLE
WHERE TO_CHAR(DATETIME,'SS') <'15'
GROUP BY TO_CHAR(DATETIME,'YYYY-MM-DD'), AGROUP
ORDER BY AGROUP

答案 3 :(得分:1)

select dateTime, agroup
  from (select dateTime, agroup, 
               row_number() over (partition by agroup, trunc(datetime)
                                  order by datetime desc) rn
          from yourtab
         where to_number(to_char(datetime, 'hh24miss')) < 15)
 where rn = 1

会这样做。见http://sqlfiddle.com/#!4/b4eb98/1