我想按小时,分钟,天分组。这该怎么做?

时间:2013-07-09 02:52:36

标签: sql oracle-sqldeveloper

我有一张桌子:

CREATE TABLE SYSTEM.DATA
(
    USER VARCHAR2(20 BYTE),
    TIME  DATE,
);

INSERT INTO DATA ("USER", "TIME") VALUES ('A', '2013/3/24 AM 04:00:45');
INSERT INTO DATA ("USER", "TIME") VALUES ('B', '2013/03/24 PM 03:51:18');
INSERT INTO DATA ("USER", "TIME") VALUES ('C', '2013/03/24 PM 03:57:49');
INSERT INTO DATA ("USER", "TIME") VALUES ('D', '2013/03/25 AM 10:05:30');
INSERT INTO DATA ("USER", "TIME") VALUES ('E', '2013/03/25 AM 10:11:30');

我如何得到每天的数量(今天AM7:30,明天AM7:29结束)?像这样

DATE   | COUNT
03/23  |     1   ~~~THIS IS 'A', '2013/3/24 AM 04:00:45'
03/24  |     2
03/25  |     2

2 个答案:

答案 0 :(得分:2)

从“时间”减去7.5小时并将其用于汇总:

select to_char("time" - 7.5/24, 'YYYY-MM-DD') as thedate, count(*)
from "data"
group by to_char("time" - 7.5/24, 'YYYY-MM-DD')
order by 1

答案 1 :(得分:0)

这是MS Sql Server的解决方案。 (我不熟悉Oracle,但我想类似的东西也是如此。)@date_begin@date_end是您可以用于您想要获得的日期间隔的参数结果。这个解决方案与Gordon Linoff建议的不同之处在于它将为data表中没有项目的日期返回零,而他的查询将仅返回具有正值的日期。

    with dates (date_item) as
    (
        select dateadd(minute,450,cast(@date_begin as datetime)) as date_item
        union all
        select dateadd(dd,1,d.date_item) as date_item from dates d where d.date_item<@date_end
    )
    select
        dateadd(day, 0, datediff(day, 0, dates.date_item)),
        sum(case when data.[time]>=dates.date_item and data.[time]<dateadd(day,1,dates.date_item) then 1 else 0 end)
    from dates
    left outer join data on 1=1
    group by
        dates.date_item;