TSQL - 如何优化查询?

时间:2011-11-24 06:41:42

标签: sql-server algorithm tsql

我有新闻的表格

News
-------
NewsId
NewsText
CREATED_DATE 

我需要从指定日期到未知日期获取新闻,但结果应包含5天的新闻。

例如:

  • 如果我有与这些日期相关的新闻:29日,28日,27日,5日,4日,3日 并且指定的开始日期为29日,我需要获取创建日期在29和4之间的新闻。

我不知道如何在没有蛮力的情况下获得低日期(第4名):

declare @highDate date = '2011-09-20';
declare @rows int = 0;
declare @lowDate date = @highDate;
declare @i int = 0;

--Querying while rows count != 5
WHILE (@rows != 5)
BEGIN

    if (@i = 60) 
        break;

    set @i = @i + 1;
    set @lowDate = (select DATEADD(day, -1, @lowDate));

    set @rows = (select COUNT(*) from
        (SELECT DAY(CAST(CREATED_DATE AS date)) as c1
        FROM .[dbo].[NEWS]
        and CREATED_DATE > @lowDate
        and CREATED_DATE < @highDate
        group by DAY(CAST(CREATED_DATE AS date))) as rowsCount);
END

--then return news between to known dates
SELECT *
FROM [dbo].[NEWS]
and CREATED_DATE > @lowDate
and CREATED_DATE < @highDate
order by CREATED_DATE desc

我猜在该算法中对DB有太多疑问,我想摆脱60天的限制

2 个答案:

答案 0 :(得分:3)

declare @highDate date = '2011-09-20'

select * from (
    select *,
           dense_rank() over (order by cast(created_date as date) desc) rnk 
    from News
    where CREATED_DATE <= @highDate
) as t
where t.rnk <= 5

答案 1 :(得分:2)

这可能适合你。

declare @HighDate date = '2011-11-29'
declare @LowDate date

select @LowDate = min(N3.created_date)
from (
      select top(5) N2.created_date
      from (
            select distinct cast(N1.created_date as date) as created_date
            from news as N1
            where cast(N1.created_date as date) <= @HighDate
           ) as N2
      order by 1 desc
     ) as N3  

或者您可以使用dense_rank

select @LowDate = N.created_date
from (
      select created_date,
             dense_rank() over(order by cast(created_date as date) desc) as rn
      from News 
      where cast(created_date as date) <= @HighDate 
     ) as N
where N.rn = 5