#SQL - 排序首先匹配记录

时间:2016-10-28 18:48:27

标签: sql sql-server sql-server-2008

我需要帮助订购此表(命名为"赛季"),将实际日期与BEGINDATE匹配

ID          NAME                 BEGINDATE
----------- -------------------- ----------
1           2014-2015            2014-10-01
2           2015-2016            2015-10-01
3           2016-2017            2016-10-01
4           2017-2018            2017-10-01

例如: 实际日期是2016/10/28所以我们是2016-2017赛季(id = 3) 所以结果应该是

ID          NAME                 BEGINDATE
----------- -------------------- ----------
3           2016-2017            2016-10-01
1           2014-2015            2014-10-01
2           2015-2016            2015-10-01
4           2017-2018            2017-10-01

更新(已解决)

我最终做的是:

DECLARE @IDACTIVE AS INT = (SELECT MAX(ID) FROM SEASON WHERE BEGINDATE < GETDATE())

SELECT 
1 AS ORDERBY,
ID,
NAME,
BEGINDATE
FROM SEASON
WHERE ID = @IDACTIVE

UNION

SELECT 
2 AS ORDERBY,
ID,
NAME,
BEGINDATE
FROM SEASON
WHERE ID = @IDACTIVE

3 个答案:

答案 0 :(得分:0)

首先将所有未来日期移至最后,然后按beginDate排序

SELECT *
FROM season
ORDER BY CASE WHEN beginDate > GETDATE() THEN 0 ELSE 1 END,
   beginDate

答案 1 :(得分:0)

遵循下一个方法:

1)使用TopWhere条款获取唯一匹配的行。

2)获取除第1点

之外的所有记录

3)使用UNION ALL组合两个选择的结果。

<强>演示: -

Create table season (id int , NAME varchar(20),BEGINDATE date)

go
insert into season values (1,'2014-2015','2014-10-01')
insert into season values (2,'2015-2016','2015-10-01')
insert into season values (3,'2016-2017','2016-10-01')
insert into season values (4,'2017-2018','2017-10-01')

go

select  * from (
    select top 1 * from season
    where BEGINDATE < getdate()
    order by BEGINDATE desc
) a

union all

select * from season 
where BEGINDATE != (
            select top 1 BEGINDATE from season
            where BEGINDATE < getdate()
            order by BEGINDATE desc)

-- an another Soluation 

select * from season
where DATEPART(Year,BEGINDATE) =DATEPART(Year,getdate())

union all

select * from season 
where DATEPART(Year,BEGINDATE) !=DATEPART(Year,getdate())

结果:

enter image description here

答案 2 :(得分:0)

我认为使用窗口函数最容易做到这一点:

select s.*
from season s
order by (case when begindate = max(case when getdate() >= begindate then begindate end) over ()
               then 1 else 2
          end),
         id