如何选择过去5天的日期?

时间:2017-05-30 13:52:38

标签: sql sql-server

如何选择给定日期的最后5天?

给定日期:2015-11-14

选择查询应该返回如下输出 -

2015-11-14
2015-11-13
2015-11-12
2015-11-11
2015-11-10

4 个答案:

答案 0 :(得分:0)

您可以使用递归CTE:

with dates as (
      select cast(getdate() as date) as dte
      union all
      select dateadd(day, -1, dte)
      from dates
      where datediff(day, dte, getdate()) <= 4
     )
select  *
from dates
order by dte desc;

显然,您可以引用任何其他日期而不是getdate()。您的示例表明当前日期是2015-11-14,这是前一段时间。

答案 1 :(得分:0)

您可以使用下面的计数表

 Declare @dt date = getdate()       
 Select top (5) Dt = DateAdd(day, -Row_number() over (order by (select null)), @dt) from master..spt_values

答案 2 :(得分:0)

DECLARE @startdate date = getdate();
DECLARE @NbDays int = 5;

WITH ListDate AS (
SELECT 1 as LP, @startdate as Dt
UNION ALL
SELECT LP + 1, DATEADD(DAY,-1,Dt)
FROM ListDate 
WHERE LP < @NbDays 
)

SELECT * FROM ListDate; 

答案 3 :(得分:-1)

DECLARE @fromData date = getdate()
DECLARE @daysBack int = 5

;WITH dates AS (

    SELECT 1 as LP, @fromData as Dates
    UNION ALL
    SELECT LP + 1, DATEADD(DAY,-1,@fromData)
    FROM dates
    WHERE LP < @daysBack
)

SELECT * 
FROM dates