Skip to content
Advertisement

Is there a way to group by part of a datetime column in SQL?

I have a dataframe something like this.

Time                           DollarVal
2020-06-25 17:48:13.636          1000
2020-06-27 17:48:13.895          1000
2020-06-27 17:48:14.101          1000
2020-06-24 17:48:14.434          1000
2020-06-22 17:48:14.709          1000

is there a way to return a table that sums the dollar values based on the time down to the minute. For example:

Time          DollarVal
17:48:13        2000
17:48:14        3000

Notice that the “time” data in the original data set spans over a few days but I am only concerned with the time of day.

Thanks

Advertisement

Answer

I’m not sure if there is a way to just extract the time, but you can format it as a string:

select format_datetim(time, '%H:%i:%s') as time_only, sum(dollarval)
from t
group by time_only
order by time_only;

Or, you can just convert the value to a time (subject to Piotr’s comment):

select cast(time as time) as time_only, . . .
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement