Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by date in SQL Server

I'm having a problem with grouping in SQL Server.

I have a datetime column but I want to group only by date,

Here's my code

SELECT ProductCode,
       ProductName,
       ProductType,
       UnitPrice,QTY,
       Amount,
       (convert(varchar, TransactionDate, 101) )AS sTransactionDate
FROM DailyTransactions 
GROUP BY TransactionDate, ProductCode,
          ProductName,ProductType,UnitPrice,QTY,Amount

RESULT:

2/17/2012 appears three times because it has different times ...

like image 485
Prince Jea Avatar asked Jan 18 '23 10:01

Prince Jea


2 Answers

This should be a quick way of grouping your results by date:

SELECT  
   ProductCode,ProductName,ProductType,UnitPrice,QTY,Amount,(convert(varchar, TransactionDate, 101) )AS sTransactionDate
   FROM DailyTransactions 
   GROUP BY DATEADD(day, DATEDIFF(day, 0, TransactionDate), 0), ProductCode,ProductName,ProductType,UnitPrice,QTY,Amount

In this case we are getting the difference between the start of the day and the time in the date and then removing it.

like image 92
Bruno Silva Avatar answered Jan 20 '23 01:01

Bruno Silva


You could try:

GROUP BY
  DATEPART(year, TransactionDate),
  DATEPART(month, TransactionDate),
  DATEPART(day, TransactionDate)
like image 26
John Pick Avatar answered Jan 20 '23 00:01

John Pick