优化查询少于日期

时间:2020-08-23 18:33:59

标签: sql-server

我有一个如下所示的SQL查询。我想使用Less_datedate列在其中查找日期。有没有一种方法可以做而无需再次编写Less_date的代码?

select 
    *, 
    select top 1 (date) as Less_date 
    from table1 T2 
    where some complex conditions and 
    where date is < table1.date
    order by date DESC,
    select top 1 (date) as between_date 
    from table1 T3
    where date < t5 and date >t5.Less_date from table1
    and some complex condition
    order by date DESC
from
    table1 
where some complex conditions

现在,我发现这样做的唯一方法是在下面,但我想看看是否有更好的方法可以做到这一点。

select *, (select top 1 (date) as between_date from table1 T3
           where date < t5 and date >t5.Less_date
          and some complex condition
          order by date DESC) from
(
select *, 
          (select top 1 (date) as Less_date from table1 T2 
          where some complex conditions and where date is < table1.date
          order by date DESC)
from table1 
where some complex conditions
) t5

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全了解您要根据2个SELECT子查询在第一个查询中执行的操作,因此这可能无关紧要,但是您始终可以使用MAX(date_col)函数返回最新日期,而不是您正在使用的SELECT TOP 1或ORDER BY date_col DESC方法。

如果您只是想让两列之间的日期相同,可以执行以下操作:

SELECT MAX(date_col1) FROM table1 INNER JOIN table 1 ON table1.date_col1 = table1.date_col2

或者您可以使用SELECT *来获取两列之间的所有公共日期。