1

假设我有以下 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

4 回答 4

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

于 2013-04-03T12:48:49.443 回答
1

TRUNC 函数非常方便提取天数:

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 则过滤。

于 2013-04-03T12:50:44.390 回答
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
于 2013-04-03T12:54:40.377 回答
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

于 2013-04-03T12:56:26.013 回答