I have a table with such a structure
CREATE TABLE UsersHistory ( Id INT IDENTITY, UserID INT, StatusId INT, CreateTime DATETIME, ChangedTime DATETIME ) INSERT INTO UsersHistory(UserID, StatusId, CreateTime, ChangedTime) SELECT 1,1,'20150414','20150414' UNION ALL SELECT 1,2,'20150414','20150415' UNION ALL SELECT 1,3,'20150414','20150416' UNION ALL SELECT 2,1,'20150413','20150413' UNION ALL SELECT 2,3,'20150413','20150416'
and request
;WITH k AS ( SELECT uh.UserID,MAX(uh.ChangedTime) AS Dt FROM UsersHistory AS uh WHERE uh.ChangedTime<'20150416' GROUP BY uh.UserID ) SELECT k.UserID,uh.StatusId FROM k INNER JOIN UsersHistory AS uh ON k.UserID = uh.UserID AND k.Dt = uh.ChangedTime
The request is too simple and needs no further explanation. I want to simplify this. (Delete a connection with a date and time type column).
Any suggestion?
source share