Combining ORDER BY AND UNION in SQL Server

后端 未结 4 1059
渐次进展
渐次进展 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:48

    If you're working on SQL Server 2005 or later:

    ; 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
    

    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)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-05 07:02
    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
    
    0 讨论(0)
  • 2020-12-05 07:08
    SELECT TOP 1 Id as sameColumn,Name FROM Locations 
    UNION ALL
    SELECT TOP 1 Id as sameColumn,Name FROM Locations ORDER BY sameColumn DESC
    
    0 讨论(0)
提交回复
热议问题