/*第一種實現方法,效率低並且有錯誤*/ DECLARE @DD DATETIME SET @DD = GETDATE() SELECT a.GoodsID , a.Account , a.LastUpdate FROM dbo.tb_App_Goods a LEFT JOIN dbo.tb_App_Goods b ON a.Account = b.Account AND a.LastUpdate > b.LastUpdate GROUP BY a.GoodsID , a.Account , a.LastUpdate HAVING COUNT(b.GoodsID) < 2 ORDER BY a.Account , a.LastUpdate DESC; PRINT DATEDIFF(MILLISECOND, @DD, GETDATE()) /*第二種實現方法,效率高並且准確*/ SET @DD = GETDATE() SELECT a.GoodsID , a.Account , a.LastUpdate FROM dbo.tb_App_Goods AS a LEFT JOIN ( SELECT ROW_NUMBER() OVER ( PARTITION BY Account ORDER BY LastUpdate DESC ) AS C , * FROM dbo.tb_App_Goods ) AS b ON a.GoodsID = b.GoodsID WHERE ( b.C BETWEEN 1 AND 2 ) ORDER BY a.Account , a.LastUpdate DESC; PRINT DATEDIFF(MILLISECOND, @DD, GETDATE())
執行結果:
明顯第二種方法效率最高:
不僅僅是效率高,仔細看,查詢結果不一樣,第一種方法結果比第二種方法查詢出來的多:
原因:
第一種方法什么鬼,查詢出來的還不夠准確,,
總結:一定要用第二種方法
特此記錄,,


