我正在使用Microsoft SQL Server。我有以下查询,它按预期返回选择的列,排名和按end_date排序的查询。 end_date的类型为datetime。
select
rank() over (order by end_date desc) rownum,
salary, name, end_date
from
employee
order by
end_date desc
如何修改和/或添加它以仅提取返回的第一行?可以通过对上述查询进行修改来完成,还是必须添加其他逻辑?
答案 0 :(得分:4)
使用子查询:
SELECT *
FROM (select rank() over (order by endmonth desc) rownum,
salary, name, endmonth
from employee e) s
WHERE rownum = 1;
或WITH TIES
选项(特定于SQL Server-可能会生成较差的执行计划):
select TOP 1 WITH TIES rank() over (order by endmonth desc) rownum,
salary, name, endmonth, name
from employee e
order by rownum
答案 1 :(得分:3)
通常,最快的方法(具有正确的索引)是相关子查询:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
您想要的索引位于select 1 as rownum, salary, name, endmonth, name
from employee e
where e.endmonth = (select max(e2.endmonth)
from employee e2
);
上。
如果您知道会有一行,那么将employee(endmonth)
与order by
(或与您的数据库等效)是最好的方法:
fetch first
如果您的数据库支持select 1 as rownum, salary, name, endmonth, name
from employee e
order by e.endmonth desc
fetch first one row only;
,则可以使用它。例如,在SQL Server中:
with ties
答案 2 :(得分:0)
就像Lukasz所说的那样,但是您也可以使用ROW_NUMBER,它不会像RANK一样返回重复的值,因此您可以首先明确地获得一行。
查看:SQL RANK() versus ROW_NUMBER()
SELECT *
FROM (select ROW_NUMBER() over (order by endmonth desc) rownum,
salary, name, endmonth, name
from employee e) s
WHERE rownum = 1;
答案 3 :(得分:0)
select rank() over (order by endmonth desc) rownum, salary, name,
endmonth, name
from employee e
limit 1;
希望这会有所帮助