如何选择最后一行到顶部但仍然按顺序从第一行到最后一行

时间:2017-06-21 08:03:21

标签: sql sql-server

使用SQL Server,我想使用查询选择一行,它在顶部显示最后一行,但仍然按顺序显示另一行。例如 : 如果我有这样的东西

<table border="1px">
      <tr><th>Firstname</th><th>Lastname</th><th>Month of Birth</th></tr>
      <tr><td>Jill</td><td>Smith</td><td>January</td></tr>
      <tr><td>Eve</td><td>Jackson</td><td>February</td></tr>
      <tr><td>Jane</td><td>Doe</td><td>March</td></tr>
      <tr><td>Danny</td><td>Prince</td><td>April</td></tr>
    </table>

然后我想展示这样的东西:

<table border="1px">
      <tr><th>Firstname</th><th>Lastname</th><th>Month of Birth</th></tr>
      <tr><td>Danny</td><td>Prince</td><td>April</td></tr>
      <tr><td>Jill</td><td>Smith</td><td>January</td></tr>
      <tr><td>Eve</td><td>Jackson</td><td>February</td></tr>
      <tr><td>Jane</td><td>Doe</td><td>March</td></tr>
    </table>

是否可以在1个查询中执行此操作?如果有可能,怎么样? 我感谢任何帮助,谢谢

2 个答案:

答案 0 :(得分:1)

试试这个:

declare @tbMos table(Mname nvarchar(50),num int)
insert into @tbMos
select 'January',1 union all
select 'February',2 union all
select 'March',3 union all
select 'April',4 union all
select 'May',5 union all
select 'June',6 union all
select 'July',7 union all
select 'August',8 union all
select 'September',9 union all
select 'October',10 union all
select 'November',11 union all
select 'December',12

declare @tb table(Firstname nvarchar(50),Lastname nvarchar(50),[MonthName] nvarchar(50))
Insert into @tb
select 'Jill','Smith','January' union all
select 'Eve','Jackson','February' union all
select 'Jane','Doe','March' union all
select 'Danny','Prince','April'

declare @LastMname varchar(50)
select top 1 @LastMname = [Monthname] from @tb order by [Monthname]

;with cte as(
  select firstname,lastname,[monthname],mname,num from
(select * from
(select * from @tb where [monthname] <>@LastMname ) as a) as a
left join  
(select * from @tbmos) as b on 
a.[monthname] = b.mname 
)

select firstname,lastname,[monthname] from
(select * from cte
union all
select *,'lastmname',0 from
(select top 1 * from @tb order by [Monthname]) as a) as a
order by num

结果:

Danny   Prince  April
Jill    Smith   January
Eve     Jackson February
Jane    Doe     March

答案 1 :(得分:0)

演示

create table tt (
    x int,
    );

insert tt(x) 
values (1),(20),(17),(8);

select x 
from( 
    select x, case Row_number() over(order by x DESC) when 1 then 2147483647 -- max int
       else Row_number() over(order by x DESC) end rn
    from tt
    ) t
order by rn DESC;