Combining ORDER BY AND UNION in SQL Server

后端 未结 4 1078
渐次进展
渐次进展 2020-12-05 06:06

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
         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 06:56

    Put your order by and top statements into sub-queries:

    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
    

提交回复
热议问题