Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by DATE only in column datetime

Tags:

sql

sql-server

I'm having a problem with grouping in SQL Server Express 2005

I have a DATETIME COLUMN but i want to group it only by date.

Here my SQL Statement:

SELECT (u.FirstName + ' ' + u.LastName) AS [FullName],d.user_id,CONVERT(varchar,d.log_date,101) AS log_date, min(d.login_time) as LOG_IN, max(d.logout_time) as LOG_OUT, sum(d.totaltime) as TOTHrs 
FROM tbldtr d INNER JOIN tblUsers u ON d.user_id = u.User_Id
WHERE d.user_id = 'ADMIN1' and d.log_date BETWEEN '6/1/2013' AND '6/15/2013'
GROUP BY DATEADD(day, DATEDIFF(day, 0, log_date), 0),u.FirstName,u.LastName,d.user_id order by d.log_date asc

but it give me this error:

Column 'tbldtr.log_date' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Thanks in advance.!

like image 930
Unknownymous Avatar asked Sep 05 '13 09:09

Unknownymous


1 Answers

Just move convert(varchar,d.log_date,101) into group by clause:

select
    u.FirstName + ' ' + u.LastName as [FullName],
    d.user_id,
    convert(varchar, d.log_date, 101) as log_date,
    min(d.login_time) as LOG_IN,
    max(d.logout_time) as LOG_OUT,
    sum(d.totaltime) as TOTHrs 
from tbldtr d
    inner join tblUsers u on d.user_id = u.User_Id
where d.user_id = 'ADMIN1' and d.log_date between '20130601' AND '20130615'
group by
     convert(varchar, d.log_date, 101),
     u.FirstName, u.LastName, d.user_id
order by log_date asc

Also, it's more safe to change dates in the where into unambiguous format - YYYYMMDD

like image 140
Roman Pekar Avatar answered Sep 28 '22 17:09

Roman Pekar