Sql 如何选择顶部的最后一行,但仍让另一行按从第一行到最后一行的顺序排列

Sql 如何选择顶部的最后一行,但仍让另一行按从第一行到最后一行的顺序排列,sql,sql-server,Sql,Sql Server,使用SQL Server,我希望使用查询选择某一行,在该行的顶部显示最后一行,但仍让另一行按顺序显示。例如: 如果我得到这样的东西 姓氏姓氏出生月份 吉尔史密斯一月份 二月一日 珍妮多马奇 丹尼普利 演示 试试这个: declare @tbMos table(Mname nvarchar(50),num int) insert into @tbMos select 'January',1 union all select 'February',2 union all select 'Marc

使用SQL Server,我希望使用查询选择某一行,在该行的顶部显示最后一行,但仍让另一行按顺序显示。例如: 如果我得到这样的东西


姓氏姓氏出生月份
吉尔史密斯一月份
二月一日
珍妮多马奇
丹尼普利
演示

试试这个:

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

是的,这是可能的。如果需要更多详细信息,请提供表DDL和样本数据插入。这将首先根据上面的样本获取最后一个月,然后按升序获取剩余月份。从一月到十二月。
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