我的SELECT
查询中遇到GROUP BY
和DATEADD
的问题,它是这样的:(请参阅下面的示例sql代码)
SELECT
'USER1' AS [user_id],
DATEADD(hh,-15,log_date) AS [LogDate],
MIN(DATEADD(hh,-15,login_time)) AS [Login],
MAX(DATEADD(hh,-15,logout_time)) AS [Logout],
DATEDIFF(MINUTE,MIN(DATEADD(hh,-15,login_time)),
MAX(DATEADD(hh,-15,logout_time)))/60.0 AS [TotalHrs]
FROM
tblDTR
WHERE
user_id = 'USER1'
AND log_date BETWEEN CAST('02/07/2014' AS datetime)
AND CAST('02/28/2014' AS datetime)
GROUP BY
user_id,
DATEADD(hh, -15, log_date)
ORDER BY
LogDate ASC
这就是结果:
我想要做的是LogDate
列必须显示 REAL DATE& TIME (意味着,列不得减去 -15 ),以及正如您在LogDate
列上方的结果表中看到的那样,虽然我使用GROUP BY DATEADD(hh, -15, log_date)
但它根本不起作用。我错过了SQL代码的某些功能吗?
这是我的新SQL代码,用于显示LogDate
而减去15 :
SELECT
'USER1' AS [user_id],
CONVERT(varchar,log_date,101) AS [LogDate], <-- I changed here but it didn't work, it give me error.
MIN(DATEADD(hh, -15, login_time)) AS [Login],
MAX(DATEADD(hh, -15, logout_time)) AS [Logout],
DATEDIFF(MINUTE, MIN(DATEADD(hh, -15, login_time)),
MAX(DATEADD(hh, -15, logout_time)))/60.0 AS [TotalHrs]
FROM
tblDTR
WHERE
user_id = 'USER1'
AND log_date BETWEEN CAST('02/07/2014' AS datetime)
AND CAST('02/28/2014' AS datetime)
GROUP BY
user_id,
DATEADD(hh, -15, log_date)
ORDER BY
LogDate ASC
错误:
Msg 8120,Level 16,State 1,Line 3
专栏&#39; tblDTR.log_date&#39;在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
非常感谢任何替代方案和建议。谢谢!
修改 顺便说一下,我使用的是SQL Server 2012
输出必须:
-------------------------------------------------------------------------
| user_id | LogDate | Login | LogOut | TotalHrs |
-------------------------------------------------------------------------
| USER1 | 02/07/2014 | 2014-02-07 08:12 | 2014-02-07 19:30 | 11.28 |
-------------------------------------------------------------------------
答案 0 :(得分:1)
你可以简单地用另一个选择包裹你的选择,加上15个小时:
SELECT [user_id],
DATEADD(hh, 15 ,LogDate) AS [LogDate],
[Login],
[Logout],
[TotalHrs]
FROM (
SELECT
'USER1' AS [user_id],
DATEADD(hh,-15,log_date) AS [LogDate],
MIN(DATEADD(hh,-15,login_time)) AS [Login],
MAX(DATEADD(hh,-15,logout_time)) AS [Logout],
DATEDIFF(MINUTE,MIN(DATEADD(hh,-15,login_time)),
MAX(DATEADD(hh,-15,logout_time)))/60.0 AS [TotalHrs]
FROM tblDTR
WHERE user_id = 'USER1'
AND log_date
BETWEEN CAST('02/07/2014' AS datetime)
AND CAST('02/28/2014' AS datetime)
GROUP BY
user_id,
DATEADD(hh,-15,log_date)
) InnerQueryAlias
ORDER BY LogDate ASC
答案 1 :(得分:0)
在查询的GROUP BY子句中,替换
DATEADD(hh,-15,log_date)
带
tblDTR.log_date