我需要幫助才能在一天內只選擇最後一個更新的行進入/退出。Query to select one row for one date in SQL Server
我使用這個查詢:
SELECT
convert(nvarchar(20), EmpID) as EmpID, ID,
DATENAME(dw, date1) AS day, date1 AS date,
PunchDateTime AS timein,
COALESCE((SELECT MAX(PunchDateTime) AS Expr1
FROM PunchData AS b
WHERE empid = '61039'
AND (EmpID = a.EmpID)
AND (PunchType = 4)
AND PunchDateTime between a.PunchDateTime and dateadd(hour, 17, a.PunchDateTime)),
(SELECT MIN(PunchDateTime) AS Expr1
FROM PunchData AS b
WHERE empid = '61039'
AND (EmpID = a.EmpID)
AND (ID >= a.ID)
AND (PunchType = 1)
AND date1 = a.date1), 0) AS timeout
FROM
dbo.PunchData AS a
WHERE
empid = '61039'
AND (PunchType = 1)
GROUP BY
EmpID, ID, DATENAME(dw, date1), date1, PunchDateTime
UNION ALL
SELECT
convert(nvarchar(20), EmpID) as EmpID, ID,
DATENAME(dw, dateadd(hour, -12, PunchDateTime)) AS day,
convert(date, COALESCE((SELECT Min(PunchDateTime) AS Expr1
FROM PunchData AS b
WHERE EmpID = '61039'
AND (EmpID = a.EmpID)
AND (PunchType = 1)
AND PunchDateTime between dateadd(hour, -17, a.PunchDateTime)
and a.PunchDateTime),
dateadd(hour, -12, PunchDateTime))) AS date,
COALESCE((SELECT Min(PunchDateTime) AS Expr1
FROM PunchData AS b
WHERE EmpID = '61039'
AND (EmpID = a.EmpID)
AND (PunchType = 1)
AND PunchDateTime between dateadd(hour, -17, a.PunchDateTime)
and a.PunchDateTime),
(SELECT Max(PunchDateTime) AS Expr1
FROM PunchData AS b
WHERE EmpID = '61039'
AND (EmpID = a.EmpID)
AND (ID = a.ID)
AND (PunchType = 4)
AND date1 = a.date1), 0) AS timein,
PunchDateTime as timeout
FROM
dbo.PunchData AS a
WHERE
(PunchType = 4)
AND empid = '61039'
GROUP BY
EmpID, ID, DATENAME(dw, date1), date1, PunchDateTime
你應該作出努力,是** **一致的與您如何編寫SQL關鍵字 - * *要麼把它們寫在所有大寫('SELECT','FROM ','CONVERT'),或者將它們寫成全部小寫字母(select,from,convert)或混合大小寫形式(Select,From,Convert) - 但請**選取一種樣式**然後**粘貼它* * - 不要將它們全部混合在一起! –