获取最新记录和之前的先前记录

时间:2019-11-05 08:39:37

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

我需要有关如何优化代码的帮助。我要在这里选择的是最近的计划年度和之前的先前的计划年度。还假设如果ScheduleYear 2019不可用。该脚本仍将获得2018年,2017年。

select ScheduleYear
from t_year 
where (getutcdate() between yearbegin and yearend OR datepart(yy,getutcdate()) = ScheduleYear
OR ScheduleYear = (SELECT ScheduleYear-1 FROM t_year WHERE getutcdate() between yearbegin and yearend)))
and enabled = 1
order by ScheduleYear DESC

4 个答案:

答案 0 :(得分:0)

您只是在寻找.vod-player { width: 100vw; z-index: 2; margin-left: -30px; }order by吗?

top

答案 1 :(得分:0)

我认为您可以通过top和适当的排序来获得所需的结果:

position: static

答案 2 :(得分:0)

我认为这是您想要实现的。

select top 2 coalesce(ScheduleYear, year(getutcdate())) as ScheduleYear from t_year 
where (ScheduleYear between yearbegin and yearend
    or
        year(getutcdate()) between yearbegin and yearend)
and enabled = 1
order by coalesce(ScheduleYear, year(getutcdate())) desc

答案 3 :(得分:0)

如果ScheduleYear是唯一的,则可以使用:

select top (2) ScheduleYear
from t_year 
where getutcdate() >= yearbegin and enabled = 1
order by ScheduleYear desc;

如果有重复项,请使用select distinct

select distinct top (2) ScheduleYear
from t_year 
where getutcdate() >= yearbegin and enabled = 1
order by ScheduleYear desc;

除非必要,否则不要使用select distinct,因为它会增加处理开销。