在SQL Server中组合ORDER BY和UNION

时间:2011-04-05 11:27:08

标签: sql sql-server sql-order-by union-all

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

此查询失败

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

任何帮助?

4 个答案:

答案 0 :(得分:64)

将您的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

答案 1 :(得分:9)

select * from (
SELECT TOP 1 Id,Name FROM Locations ORDER BY Id) X
UNION ALL
SELECT TOP 1 Id,Name FROM Locations ORDER BY Id DESC

答案 2 :(得分:8)

如果您正在使用SQL Server 2005或更高版本:

; WITH NumberedRows as (
    SELECT Id,Name,
       ROW_NUMBER() OVER (ORDER BY Id) as rnAsc,
       ROW_NUMBER() OVER (ORDER BY Id desc) as rnDesc
    FROM
        Locations
)
select * from NumberedRows where rnAsc = 1 or rnDesc = 1

唯一不会像原始查询一样的地方是表中是否只有一行(在这种情况下,我的答案会返回一行,而你的答案会返回同一行两次)

答案 3 :(得分:5)

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