7

我在 SQL Server Express 2005 中进行分组时遇到问题

我有一个DATETIME COLUMN,但我只想按日期对它进行分组。

这是我的 SQL 语句:

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

但它给了我这个错误:

列 'tbldtr.log_date' 在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

提前致谢。!

4

4 回答 4

5

只需convert(varchar,d.log_date,101)进入group by子句:

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

此外,将日期更改where为明确的格式更安全 -YYYYMMDD

于 2013-09-05T09:54:17.623 回答
0

使用强制转换功能,它应该变成这样:

GROUP BY CAST(d.log_date AS DATE)
于 2013-09-05T09:57:41.607 回答
0

如果您convert(varchar,d.log_date,101)在组中移动,那么结果将不正确,因为它会同时计算日期和时间,因此当您在同一日期有多个条目但时间不同时,它将显示两次结果。

试试这个它会工作

SELECT ( u.firstname + ' ' + u.lastname ) AS [FullName], 
       d.user_id, 
       CONVERT(VARCHAR, cast(d.log_date  as 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 cast(d.log_date  as DATE),
          u.firstname, 
          u.lastname, 
          d.user_id 
ORDER  BY d.log_date ASC 
于 2013-09-05T09:57:58.107 回答
0

尝试使用以下内容:

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 (u.FirstName + ' ' + u.LastName), d.user_id, CONVERT(varchar,d.log_date,101)
order by d.log_date asc
于 2013-09-05T09:58:19.733 回答