在特定时间(跨2天)之间的多天内选择数据

时间:2019-11-21 10:45:38

标签: sql oracle date timestamp

我需要知道过去7天中在数据库中出现了多少个条目,其时间戳在23:00和01:00之间...

我遇到的问题是时间戳跨越2天,不确定在一个查询中是否甚至可以实现。

到目前为止,我已经提出了以下建议:

select trunc(timestamp) as DTE, extract(hour from timestamp) as HR, count(COLUMN) as Total
from TABLE 
where trunc(timestamp) >= '12-NOV-19' and 
      extract(hour from timestamp) in ('23','00','01') 
group by trunc(timestamp), extract(hour from timestamp)
order by 1,2 desc; 

我希望得到的结果是这样的:

DTE         |  Total
20-NOV-19       5
19-NOV-19       4
18-NOV-19       4
17-NOV-19       6

非常感谢

2 个答案:

答案 0 :(得分:1)

在一天中进行过滤,首先将其与TRUNC( SYSDATE ) - INTERVAL '7' DAY进行比较,然后通过将timestamp与本身被截断为午夜(以小时数抵消)的select trunc(timestamp) as DTE, extract(hour from timestamp) as HR, count(COLUMN) as Total from TABLE WHERE timestamp >= TRUNC( SYSDATE ) - INTERVAL '7' DAY AND ( timestamp <= TRUNC( timestamp ) + INTERVAL '01:00' HOUR TO MINUTE OR timestamp >= TRUNC( timestamp ) + INTERVAL '23:00' HOUR TO MINUTE ) group by trunc(timestamp), extract(hour from timestamp) order by DTE, HR desc; 进行比较来考虑小时数。

@Entity(name = "Person")
public static class Person {
    @ManyToMany(cascade = {CascadeType.DELETE})
    private List<Address> addresses = new ArrayList<>();
    ...
}

Person person1 = entityManager.find( Person.class, personId );
entityManager.remove( person1 );

答案 1 :(得分:0)

减去或加上一个小时以得出日期。我不确定要分配给每个期间的日期,但是主意是:

select trunc(timestamp - interval '1' hour) as DTE, 
       count(*) as Total
from t 
where trunc(timestamp - interval '1' hour) >= DATE '2019-11-12' and 
      extract(hour from timestamp) in (23, 0) 
group by trunc(timestamp - interval '1' hour)
order by 1 desc; 

注意:如果您希望在晚上11:00之前的时间和凌晨1:00,那么您希望小时为23或0。