我有表,這樣的結構簡化SQL SELECT語句
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'
和查詢
;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
查詢是太容易,而不是需要更多的解釋。我想簡化它。 (刪除加入日期時間類型列)。
有何建議?
這是當然的贏家。非常複雜的問題有時會導致非常複雜的答案。在這種情況下看到簡單是一個很好的天賦。 –