选择最新日期

时间:2012-08-09 09:48:43

标签: sql-server-2008-r2

    SELECT
    distinct  

        HRM_Employee.EmployeeId EmployeeXId,
      ([HRM_Employee].[FirstName] +' '+ISNULL([HRM_Employee].[MiddleName],' ')+' '+ISNULL([HRM_Employee].[LastName],' ')) AS FirstName     
     -- ,[FirstName]
          ,[HRM_Employee].[MiddleName]
          ,[HRM_Employee].[LastName]
          ,[HRM_Employee].[Code]          
          ,[HRM_Employee].[UserName]
          ,[HRM_Employee].[Password]
          ,[HRM_Employee].[DateOfBirth]
          ,[HRM_Employee].[OriginalBirthDate]
          ,[HRM_Employee].[Gender]
          ,[HRM_Employee].[BloodGroup]
          ,[HRM_Employee].[Height]
          ,[HRM_Employee].[MaritalStatus]
          ,[HRM_Employee].[DateOfMarriage]
          ,[HRM_Employee].[IdentificationMark1]
          ,[HRM_Employee].[IdentificationMark2]
          ,[HRM_Employee].[Religion]
          ,(SELECT [A].[FirstName] +' '+  [A].[MiddleName] +' '+ [A].[LastName] 
              FROM [dbo].[HRM_Employee] [A] WHERE [A].EmployeeId = [HRM_Transfer].[ReportingOfficerXId]  
           ) [PersonInCharge] 
          ,[HRM_Department].[Name] [DepartmentName]
          ,[HRM_Branch].[Name] [BranchName]
          ,[HRM_Division].[Name] [DivisionName]
          ,[HRM_Designation].[Name] [DesignationName]
          ,HRM_Transfer.TransferDate
    from HRM_Employee
    LEFT join [dbo].[HRM_Division]
            ON [HRM_Employee].DivisionXId  = [HRM_Division].DivisionId
            JOIN [dbo].[HRM_Designation] 
            ON [HRM_Employee].DesignationXId = [HRM_Designation].DesignationId
            JOIN [HRM_Department] 
            ON [HRM_Employee].[DepartmentXId] = [HRM_Department].[DepartmentId] 
            JOIN [HRM_Branch] 
            ON [HRM_Employee].[BranchXId] = [HRM_Branch].[BranchId] 
            INNER JOIN HRM_Transfer
            ON HRM_Transfer.EmployeeXId=HRM_Employee.EmployeeId
    WHERE 
        Convert(varchar(11),HRM_Transfer.TransferDate,103) <=Convert(varchar(11), getdate(),103)
END

当我执行此操作时,我得到的输出如下

EmployeeXId    FirstName               TransferDate
34             Ambarish   V               2012-08-09 00:00:00.000
54             Anil  N P                      2012-08-09 00:00:00.000
55         Ann  Rose Abraham              2012-08-08 00:00:00.000
55         Ann  Rose Abraham              2012-08-09 00:00:00.000
74             Anees  M S                     2012-08-09 00:00:00.000

由此我想显示最新转移日期的数据。在EmployeeId 55中,我需要显示转​​移日期为2012-08-09 00:00:00.000的数据。我想在上面的SP做什么修改来获得所需的答案?请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

按EmployeeXId分组并选择MAX(TransferDate)。