要将日期时间更改为它所在的日期,请使用:
SELECT DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0), GETDATE()
所以在你的情况下,你可以用它来比较Business_Day
SELECT Case WHEN DATEADD(d, DATEDIFF(d, 0, DATEADD(hour, -3, User_Attend_Date)), 0) = Business_Day
编辑
您实际上希望在任何一天为用户使用第一次登录,因此您可以使用 CTE 来实现此目的。我添加了一个“期望”列(您可以轻松删除),我假设您也必须有一个 user_id 来识别用户?如果是这样,请尝试:
http://sqlfiddle.com/#!3/c54b4/1
WITH AttendanceDate AS (
SELECT User_Id, User_Attend_Date, Business_Day, DATEADD(d, DATEDIFF(d, 0, DATEADD(hour, -3, User_Attend_Date)), 0) AS ActualAttendDate
FROM tblAttendance ),
FirstAttendance AS (
SELECT User_Id, ActualAttendDate, MIN(User_Attend_Date) FirstLogin
FROM AttendanceDate
GROUP BY User_Id, ActualAttendDate
)
SELECT TA.User_Id, TA.User_Attend_Date, TA.Business_Day, FA.FirstLogin
FROM AttendanceDate AS TA
INNER JOIN FirstAttendance AS FA
ON TA.User_Id = FA.User_Id
AND TA.ActualAttendDate = FA.ActualAttendDate
请注意,演员表现在有点多余:http ://sqlfiddle.com/#!3/c54b4/2 ,并且要与多个用户一起查看:http ://sqlfiddle.com/#!3/4f2c7/1 。最终结果,没有Expect
列在http://sqlfiddle.com/#!3/e9e6c/1上。
编辑 2
如果您不需要 User_Id 分组,那么它就像(http://sqlfiddle.com/#!3/0daab/1)一样简单:
WITH AttendanceDate AS (
SELECT User_Attend_Date, Business_Day, DATEADD(d, DATEDIFF(d, 0, DATEADD(hour, -3, User_Attend_Date)), 0) AS ActualAttendDate
FROM tblAttendance ),
FirstAttendance AS (
SELECT ActualAttendDate, MIN(User_Attend_Date) FirstLogin
FROM AttendanceDate
GROUP BY ActualAttendDate
)
SELECT TA.User_Attend_Date, TA.Business_Day, FA.FirstLogin
FROM AttendanceDate AS TA
INNER JOIN FirstAttendance AS FA
ON TA.ActualAttendDate = FA.ActualAttendDate
原始答案(根据解释预期结果如何组合的新信息不再相关)
完整(http://sqlfiddle.com/#!3/fa5bb/10):
SELECT User_Attend_Date, DATEADD(hour, -3, User_Attend_Date),
DATEADD(d, DATEDIFF(d, 0, DATEADD(hour, -3, User_Attend_Date)), 0) AS 'ForClarity1',
CAST(DATEADD(d, DATEDIFF(d, 0, DATEADD(hour, -3, User_Attend_Date)), 0) AS DATE) AS 'ForClarity2',
Business_Day AS 'ForClarity3',
Case WHEN
CAST(DATEADD(d, DATEDIFF(d, 0, DATEADD(hour, -3, User_Attend_Date)), 0) AS DATE) = Business_Day
THEN User_Attend_Date ELSE Business_Day END As 'Check_Same_Day'
FROM dbo.tblAttendance