We have a table which will capture the swipe record of each employee
. I am trying to write a query to fetch the list of distinct employee record by the first swipe for today.
We are saving the swipe date info in datetime
column. Here is my query its throwing exception.
select distinct
[employee number], [Employee First Name]
,[Employee Last Name]
,min([DateTime])
,[Card Number]
,[Reader Name]
,[Status]
,[Location]
from
[Interface].[dbo].[VwEmpSwipeDetail]
group by
[employee number]
where
[datetime] = CURDATE();
Getting error:
Column 'Interface.dbo.VwEmpSwipeDetail.Employee First Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Any help please?
Thanks in advance.
Please Try Below Query :
First find the first timestamp for each employee on the given day (CURDATE), then join back to the main table to get all the details:
This should not be marked as mysql as this would not happen in mysql.
sql-server does not know which of the grouped [Employee First Name] values to return so you need to add an aggregate (even if you only actually expect one result). min/max will both work in that case. The same would apply to all the other rows where they are not in the GROUP BY or have an aggregate function (EG min) around them.
The error says it all:
Saying that, there are other columns that need attention too.
Either reduce the columns returned to only those needed or include the columns in your
GROUP BY
clause or add aggregate functions (MIN/MAX). Also, yourWHERE
clause should be placed before theGROUP BY
.Try:
I've removed
status
andlocation
as this is likely to return non-distinct values. In order to return this data, you may need a subquery (or CTE) that first gets the unique IDs of theSwipeDetails
table, and from this list you can join on to the other data, something like: