选择MAX,但要显示其他列

时间:2016-09-10 15:12:17

标签: sql-server sql-server-2014

哦,我有这些数据:

Copy

如果我这样做:

INSERT INTO JobHistory(EmployeeID, EffDate, EffSeq, EmploymentStatus,
JobTitle, Salary, ActionDesc)
VALUES
(1000,'07-31-2008',1,'A','Intern',2000,'New Hire'),
(1000,'05-31-2009',1,'A','Production Technician',2000,'Title Change'),
(1000,'05-31-2009',2,'A','Production Technician',2500,'Salary Change'),
(1000,'11-01-2009',1,'A','Production Technician',3000,'Salary Change'),
(1200,'01-10-2009',1,'A','Design Engineer',5000,'New Hire'),
(1200,'05-01-2009',1,'T','Design Engineer',5000,'Termination'),
(1100,'08-01-2008',1,'A','Accounts Payable Specialist I',2500,'New Hire'),
(1100,'05-03-2009',1,'A','Accounts Payable Specialist II',2500,'Title Change'),
(1100,'05-01-2009',2,'A','Accounts Payable Specialist II',3000,'Salary Change');

您将获得MAX EffData(11-01-2009)。好。但现在您只会看到列:EffData。但我还想显示EmployeeID和JobTitle,只返回记录。但你无法做到这一点,因为你必须使用SELECT MAX(EffDate) as MaxDate--, EmployeeID, JobTitle FROM JobHistory 。而且你将返回更多记录

与CTE相关也是不可能的。

那么如何只返回一条记录(Effdata的最大值),还显示了EmployeeID和jobtitle?

谢谢

1 个答案:

答案 0 :(得分:1)

您需要TOP 1 Order by而非Max汇总

SELECT Top 1 EffDate as MaxDate, EmployeeID, JobTitle
FROM JobHistory
Order by MaxDate desc

如果最大EffDate中有一个领带,那么你想看到领带记录然后使用TOP 1 with Ties

SELECT Top 1 with Ties EffDate as MaxDate, EmployeeID, JobTitle
FROM JobHistory
Order by MaxDate desc