按日期(小时)的SQL组

时间:2011-02-24 22:34:56

标签: sql oracle

我有一个带有“日期”列的表。我想按小时分组到特定日期。

4 个答案:

答案 0 :(得分:51)

你也可以这样做:

SELECT TRUNC(datecol, 'HH24') FROM mytable
GROUP BY TRUNC(datecol, 'HH24');

答案 1 :(得分:27)

Select TO_CHAR(date,'HH24')
from table
where date = TO_DATE('20110224', 'YYYYMMDD')
group by TO_CHAR(date,'HH24')

答案 2 :(得分:5)

select to_char(datecol,'HH24') thehour, count(*) count_in_hour
from tbl
where datecol = date '20110224'
group by to_char(datecol,'HH24')
order by thehour asc

答案 3 :(得分:1)

或者,我会建议EXTRACT (datetime),但是(empahsis mine):

  

如果请求HOUR,MINUTE或SECOND,则expr必须评估为   表达式数据类型TIMESTAMP,TIMESTAMP WITH TIME ZONE,TIMESTAMP   与当地时区,或间隔日到第二。 DATE无效   这里,因为Oracle数据库将其视为ANSI DATE数据类型   没时间了。

因此,结果有点难看:

  SELECT EXTRACT (HOUR FROM CAST (m.a_date AS TIMESTAMP)) AS hour_,
         COUNT (*) AS count_
    FROM MY_TABLE m
GROUP BY EXTRACT (HOUR FROM CAST (m.a_date AS TIMESTAMP));