SQL每个用户最后的一条记录

SELECT [ID]
      ,[UserID]
      ,[StartDate]
      ,[EndDate]
      ,[CreateUser]
      ,[CreateDate]
      ,[LastEditUser]
      ,[LastEditDate]     
  FROM [DB_Base].[dbo].[DB_Contracts]
  ,(SELECT UserID AS U,MAX(EndDate) AS E FROM dbo.DB_Contracts GROUP BY UserID) temp
  WHERE temp.U = dbo.DB_Contracts.UserID AND temp.E = dbo.DB_Contracts.EndDate

SQL获取每个用户最后的一条记录 

 

升级版本

 SELECT dbo.DB_User.UserNumber ,
        dbo.DB_User.Name ,
        d.StartDate ,
        d.EndDate
 FROM   dbo.DB_User
        LEFT JOIN ( SELECT [ID]
      ,[UserID]
      ,[StartDate]
      ,[EndDate]
      ,[CreateUser]
      ,[CreateDate]
      ,[LastEditUser]
      ,[LastEditDate]     
  FROM [DB_Base].[dbo].[DB_Contracts]
  ,(SELECT UserID AS U,MAX(EndDate) AS E FROM dbo.DB_Contracts GROUP BY UserID) temp
  WHERE temp.U = dbo.DB_Contracts.UserID AND temp.E = dbo.DB_Contracts.EndDate ) d ON d.UserID = dbo.DB_User.ID
                  WHERE xxxxxxxx
  

  

posted on 2014-09-05 10:25  冬夜冷雨  阅读(1295)  评论(0编辑  收藏  举报

导航