在时间之前计算行数

时间:2016-01-12 14:00:47

标签: sql oracle evaluate

我有以下情况。每一行都有一个写在表上的时间戳。现在我想每天评估在早上5点之前插入了多少行以及之后插入了多少行。怎么可以做到?

3 个答案:

答案 0 :(得分:2)

您可以使用HH24格式获取24小时制的小时:

select trunc(created_Date) as the_day
       ,sum(case when to_number(to_char(created_Date,'HH24')) < 5 then 1 else 0 end) as before_five
       ,sum(case when to_number(to_char(created_Date,'HH24')) >= 5 then 1 else 0 end) as after_five
from yourtable
group by trunc(created_Date)    

根据用户对5:10的评论,显示5之前和之后的时间戳:

select trunc(created_Date) as the_day
       ,sum(case when to_number(to_char(created_Date,'HH24')) < 5 then 1 else 0 end) as before_five
       ,sum(case when to_number(to_char(created_Date,'HH24')) >= 5 then 1 else 0 end) as after_five
from (
   -- one row januar 1 just after 5:00 a.m.
   select to_Date('01/01/2015 05:10:12','dd/mm/yyyy hh24:mi:ss') as created_date from dual
   union all
   -- one row Januar 2 just before 5:00 a.m.
   select to_Date('02/01/2015 04:59:12','dd/mm/yyyy hh24:mi:ss') as created_date from dual
   )
group by trunc(created_Date);

THE_DAY,    BEFORE_FIVE,  AFTER_FIVE
02/01/2015, 1,            0
01/01/2015, 0,            1

答案 1 :(得分:0)

假设您的时间戳是DATE列:

select trunc(date_written) as day
,      count (case when (date_written-trunc(date_written))*24 < 5 then 1 end) before_5_count
,      count (case when (date_written-trunc(date_written))*24 >= 5 then 1 end) after_5_count
from   mytable
group by trunc(date_written) 

答案 2 :(得分:0)

select to_char(time_column, 'dd/mm/yyyy'),
     sum( decode ( greatest(extract(hour from time_column), 5), extract(hour from time_column), 1, 0)) post_5,
     sum( decode ( greatest(extract(hour from time_column), 5), extract(hour from time_column), 0, 1)) pre_5
from test_time
group by to_char(time_column, 'dd/mm/yyyy')