HOWTO: Group rows by day in MSSQL

This trick is usu­ally use­ful in sta­tis­tic where you need to count or sum records based on record day. Using it will help you group­ing rows by day or month depends on your needs.

real life example:

My client had an Orders table where online shop orders  were stored while his require­ment was to cre­ate a graph that will show daily and monthly orders, so the ques­tion was how to group dates when order time was dif­fer­ent? To con­vert it to var­char and then to remove time or to just group by day(orderDate),month(orderDate),yeaR(orderDate) ? Way too long, here where this trick came in use for. Basi­cally what it does is gets num­ber of days from zero day inside of date­d­iff func­tion and then adds this amount zero day to get small­date­time type back. This trick works with days and month just instead of dd call mm

code:


select sum(productPrice) as productPrice,

count(productPrice) as numOfProductsSold

from Orders

group by dateadd(dd,datediff(dd,0,orderDate),0)
Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • LinkedIn
  • StumbleUpon
  • Technorati
  • Live
  • PDF

Tags: sql

Leave a comment