列在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中

时间:2014-09-09 10:28:30

标签: sql sql-server group-by aggregate

我们有一个表格,可以捕获每个employee的滑动记录。我正在尝试编写一个查询,以便通过今天的第一次刷卡来获取不同员工记录的列表。

我们正在datetime列中保存滑动日期信息。这是我的查询它的抛出异常。

 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();

获取错误:

  

Column' Interface.dbo.VwEmpSwipeDetail.Employee First Name'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

请帮忙吗?

提前致谢。

4 个答案:

答案 0 :(得分:6)

错误说明了一切:

  

......员工名字'在选择列表中无效,因为它未包含   在聚合函数或GROUP BY子句中

说,还有其他一些栏目也需要注意。

将返回的列减少到只需要的列或包含GROUP BY子句中的列或添加聚合函数(MIN / MAX)。此外,您的WHERE子句应放在GROUP BY

之前

尝试:

select   distinct [employee number]
      ,[Employee First Name]
      ,[Employee Last Name]
      ,min([DateTime])
      ,[Card Number]
      ,min([Reader Name])
from [Interface].[dbo].[VwEmpSwipeDetail] 
where CAST([datetime] AS DATE)=CAST(GETDATE() AS DATE)
group by  [employee number], [Employee First Name], [Employee Last Name], [Card Number]

我已删除statuslocation,因为这可能会返回非明确的值。为了返回此数据,您可能需要一个首先获取SwipeDetails表的唯一ID的子查询(或CTE),并且可以从此列表中加入其他数据,如:

SELECT [employee number],[Employee First Name],[Employee Last Name].. -- other columns
FROM [YOUR_TABLE]
WHERE SwipeDetailID IN (SELECT MIN(SwipeDetailsId) as SwipeId
                        FROM SwipeDetailTable
                        WHERE CAST([datetime] AS DATE)=CAST(GETDATE() AS DATE)
                        GROUP BY [employee number])

答案 1 :(得分:3)

请尝试以下查询:

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],[Employee First Name]
          ,[Employee Last Name]
          ,[Card Number]
          ,[Reader Name]
          ,[Status]
          ,[Location] having [datetime]=GetDate();

答案 2 :(得分:2)

首先找到每个员工在给定日期的第一个时间戳(CURDATE),然后再加入主表以获取所有详细信息:

WITH x AS (
    SELECT [employee number], MIN([datetime] AS minDate
      FROM [Interface].[dbo].[VwEmpSwipeDetail]
      WHERE CAST([datetime] AS DATE) = CURDATE()
      GROUP BY [employee number]
)
select [employee number]
      ,[Employee First Name]
      ,[Employee Last Name]
      ,[DateTime]
      ,[Card Number]
      ,[Reader Name]
      ,[Status]
      ,[Location]
  from [Interface].[dbo].[VwEmpSwipeDetail] y
  JOIN x ON (x.[employee number] = y.[employee number] AND x.[minDate] =Y.[datetime]

答案 3 :(得分:1)

这不应该标记为mysql,因为这不会发生在mysql中。

sql-server不知道要返回哪个分组的[Employee First Name]值,因此您需要添加聚合(即使您实际上只期望一个结果)。 min / max将在这种情况下起作用。这同样适用于它们不在GROUP BY中的所有其他行,或者在它们周围具有聚合函数(EG min)。