简单查询以包含基于MAX的所有列

时间:2017-08-05 20:33:51

标签: sql sql-server

我已经阅读了很多其他文章,在这一点上,我认为我只是把头撞到墙上。我该如何取代这句话:

SELECT * FROM EmployeeInformation

我希望看到表EmployeeInformation中的所有列只包含最新的RateChangeDate。我试过了MAX(RateChangeDate)。可接受的输出将替换当前的Walters, Rob行:

Walters, Rob    Senior Tool Designer    29.8462 2011-12-15 00:00:00.000 rob0@adventure-works.com

MSSQL Query

5 个答案:

答案 0 :(得分:1)

Select * from EmployeeInformation
Where RateChangeDate =
    (Select Max(RateChangeDate) 
     from EmployeeInformation)

最新员工:

Select * from EmployeeInformation e
Where RateChangeDate =
    (Select Max(RateChangeDate) 
     from EmployeeInformation
     where emplyeeId = e.emplyeeId )

答案 1 :(得分:0)

With EmpInfo AS
(
  SELECT lastname + ', ' + firstname as fullname, jobtitle, rate, ratechangedate, emailaddress,
     ROW_NUMBER() OVER (PARTITION BY lastname + ', ' + firstname BY ORDER BY RateChangeDate DESC) as RN 
   --- etc all joins
)
SELECT *
FROM EmpInfo
WHERE RN = 1

答案 2 :(得分:0)

您可以使用

SELECT *
  FROM EmployeeInformation
 WHERE RateChangeDate = (SELECT TOP 1 MAX(RateChangeDate)
                           FROM EmployeeInformation)

答案 3 :(得分:0)

您可以使用row_number,如下所示:

Select top(1) with ties * from EmployeeInformation
   Order by Row_Number() over(partition by [Name] order by RateChangeDate Desc)

答案 4 :(得分:0)

您可以使用相关子查询。

像这样的东西

 SELECT * 
 FROM tablename 
 WHERE fullname IN (SELECT fullname 
                    FROM tablename 
                    WHERE Ratechangedate IN (SELECT MAX(Ratechangedate) 
                                             FROM tablename))

最内层选择选择最大日期列,然后选择此最大日期的全名列,然后选择具有此全名的所有行。