在 SQL Server 中组合 ORDER BY 和 UNION
如何获取一个结果集中表的第一条记录和最后一条记录?
此查询失败
SELECT TOP 1 Id,Name FROM Locations ORDER BY Id
UNION ALL
SELECT TOP 1 Id,Name FROM Locations ORDER BY Id DESC
有帮助吗?
How can I get first record of a table and last record of a table in one result-set?
This Query fails
SELECT TOP 1 Id,Name FROM Locations ORDER BY Id
UNION ALL
SELECT TOP 1 Id,Name FROM Locations ORDER BY Id DESC
Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将
order by
和top
语句放入子查询中:Put your
order by
andtop
statements into sub-queries:如果您使用的是 SQL Server 2005 或更高版本:
唯一与您的原始查询不同的地方是表中只有一行(在这种情况下,我的答案返回一行,而您的答案将返回同一行)两次)
If you're working on SQL Server 2005 or later:
The only place this won't be like your original query is if there's only one row in the table (in which case my answer returns one row, whereas yours would return the same row twice)