Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by date without time

I was wondering whether there was a way to group dates that are 2014-01-26 05:39:29.000 and 2014-01-26 07:45:31.000 into one day when counting them. I currently have the following code that just groups them by their unique datetime.

    SELECT ETK_ExpirationDateTime, COUNT(*) as TotalRows
    FROM History_Action 
    WHERE [State] = 4
    GROUP BY ETK_ExpirationDateTime
    ORDER BY ETK_ExpirationDateTime 

Is there a cast or something I can do to make those 2 dates above appear as one row with a total sum?

like image 328
user3712641 Avatar asked Jun 22 '15 19:06

user3712641


People also ask

Can I group by date in SQL?

To group by date part, use the GROUP BY clause and the EXTRACT() function. Pass EXTRACT() the date parts to isolate.

Is there alternative to group by?

SQL Sub-query as a GROUP BY and HAVING AlternativeYou can use a sub-query to remove the GROUP BY from the query which is using SUM aggregate function. There are many types of subqueries in Hive, but, you can use correlated subquery to calculate sum part.

How do you group dates into years in SQL?

You simply use the aggregate function (here: SUM ) with the correct column and at the end of the query you group by year . You can rename the column using the AS keyword with a new name.


2 Answers

SELECT CAST(ETK_ExpirationDateTime AS DATE) AS DATE, COUNT(*) as TotalRows
FROM History_Action 
WHERE [State] = 4
GROUP BY CAST(ETK_ExpirationDateTime AS DATE)
ORDER BY 1
like image 147
KrazzyNefarious Avatar answered Nov 13 '22 02:11

KrazzyNefarious


You can use conversion to date:

SELECT CONVERT(date, ETK_ExpirationDateTime) as ExpirationDateTime, COUNT(*) as TotalRows
FROM History_Action 
WHERE [State] = 4
GROUP BY CONVERT(date, ETK_ExpirationDateTime)
ORDER BY CONVERT(date, ETK_ExpirationDateTime) 

This only works for SQL 2008 or newer. For older versions of SQL you can use some tricky manipulation like this:

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, ETK_ExpirationDateTime)) as ExpirationDateTime, COUNT(*) as TotalRows
FROM History_Action 
WHERE [State] = 4
GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, ETK_ExpirationDateTime))
ORDER BY DATEADD(dd, 0, DATEDIFF(dd, 0, ETK_ExpirationDateTime))
like image 5
dotnetom Avatar answered Nov 13 '22 04:11

dotnetom