我希望在从另一列中减去一列后找到MAX值。我目前所用的语法似乎不起作用。
SELECT
[EmpName] as 'Employee Name',
MAX([EndYear]-[BeginYear]) as 'Total Years'
FROM
[dbo].[EMPLOYEE];
答案 0 :(得分:1)
使用RANK声明。
SELECT *,
RANK() OVER (PARTITION BY [Employee Name] ORDER BY [Total Years] DESC) AS Ranking
FROM
(
SELECT EmpName AS 'Employee Name', EndYear - BeginYear AS 'Total Years'
FROM Employee
) TotalYears
WHERE Ranking = 1
请记住,我还没有真正测试过上面的SQL,我只是从内存中编写它。我现在要启动一个数据库来检查语法。
答案 1 :(得分:1)
Max语句必须处理聚合数据,因此请添加一个组。
SELECT
[EmpName] as 'Employee Name',
MAX([EndYear]-[BeginYear]) as 'Total Years'
FROM
[dbo].[EMPLOYEE]
group by EmpName;
答案 2 :(得分:0)
你可以沿着这些方向使用......
;WITH emps AS (
SELECT
[EmpName] AS 'EmployeeName',
[EndYear] - [Begin Year] AS 'TotalYears'
FROM
[dbo].[Employee]
)
SELECT * FROM emps WHERE TotalYears = (SELECT MAX(TotalYears) FROM emps)