gpt4 book ai didi

sql - 在 SQL Server 中组合 ORDER BY 和 UNION

转载 作者:行者123 更新时间:2023-12-01 18:06:24 25 4
gpt4 key购买 nike

如何获取一个结果集中表的第一条记录和最后一条记录?

此查询失败

SELECT TOP 1 Id,Name FROM Locations ORDER BY Id
UNION ALL
SELECT TOP 1 Id,Name FROM Locations ORDER BY Id DESC

有什么帮助吗?

最佳答案

order bytop 语句放入子查询中:

select first.Id, first.Name 
from (
select top 1 *
from Locations
order by Id) first
union all
select last.Id, last.Name
from (
select top 1 *
from Locations
order by Id desc) last

关于sql - 在 SQL Server 中组合 ORDER BY 和 UNION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5551064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com