Link to home
Start Free TrialLog in
Avatar of barkome
barkomeFlag for Canada

asked on

sql server group by every 2hrs

Hello I have this code, which groups by the hour.
SELECT CAST(start_date as date) AS ForDate,
       DATEPART(hour,start_date) AS OnHour,
       COUNT(*) AS Totals , sum(Volume) 
FROM #temp wHERE ID in (1,2,3,4) 
GROUP BY CAST(start_date as date),
       DATEPART(hour,start_date)

Open in new window


Does anyone know how I can modify it to group by every 2hrs?
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Hi,

Very quick try ...

SELECT CAST(start_date as date) AS ForDate,
       (DATEPART(hour,start_date)+1) AS OnHour,
       COUNT(*) AS Totals , sum(Volume) 
FROM #temp wHERE ID in (1,2,3,4) 
GROUP BY CAST(start_date as date),
       (DATEPART(hour,start_date)+1)

Open in new window

Avatar of Scott Pletcher
Not sure of the exact details of how you want to do this, but something like:

SELECT DATEADD(HOUR, DATEDIFF(HOUR, 0, start_date) / 2 * 2, 0) AS DateAndHour,
       COUNT(*) AS Totals , sum(Volume)
FROM #temp wHERE ID in (1,2,3,4)
GROUP BY DATEADD(HOUR, DATEDIFF(HOUR, 0, start_date) / 2 * 2, 0)
Avatar of barkome

ASKER

Thanks, I forgot to mention that I would like to group by every 2hrs from 5am
SOLUTION
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial