I have a Table with a "Date" Column. I want to group by hour for a specific date.
Select TO_CHAR(date,'HH24')
from table
where date = TO_DATE('20110224', 'YYYYMMDD')
group by TO_CHAR(date,'HH24')
-
2
You can also do this:
SELECT TRUNC(datecol, 'HH24') FROM mytable
GROUP BY TRUNC(datecol, 'HH24');
-
5Another advantage is that the datatype returned by
TRUNC
here is a DATE, so it always sorts correctly - whereasTO_CHAR
will use alphabetic sorting which will not always be correct depending on what date/time format is used. – Jeffrey Kemp Feb 26 '11 at 2:21 -
This doesn't work if you want Date/hour (
TRUNC(datecol,'MM-DD-YYYY HH24')
gives error:SQL Error [1898] [22008]: ORA-01898: too many precision specifiers
) – ryvantage Aug 22 '19 at 1:44 -
@ryvantage, you can't truncate at multiple levels at the same time - if you want to truncate to the nearest day, use
DD
, if you want to truncate to the nearest hour (as per the OP), useHH24
as per my answer. – Jeffrey Kemp Aug 22 '19 at 1:53 -
-
1@Wassadamo, that'll be because you have not matched your SELECTed expression with your GROUP BY expression. – Jeffrey Kemp Jul 1 '20 at 11:39
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
Alternatively, I would have suggested EXTRACT (datetime), but (empahsis mine):
If HOUR, MINUTE, or SECOND is requested, then expr must evaluate to an expression of data type TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, or INTERVAL DAY TO SECOND. DATE is not valid here, because Oracle Database treats it as ANSI DATE data type, which has no time fields.
Therefore, the result is a little bit ugly:
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));
DateTime
then how are you going to group by part of the data in the "Date" column? – The Muffin Man Feb 24 '11 at 22:39