如何在SQL Server中选择最后七天的日期

时间:2018-07-12 13:04:54

标签: sql sql-server

我想在select语句中选择最后7天的日期,因为当前日期为2018-07-12

预期结果:

  

最后7天_日期
  2018-07-06
  2018-07-07
  2018-07-08
  2018-07-09
  2018-07-10
  2018-07-11
  2018-07-12

5 个答案:

答案 0 :(得分:5)

如果问题中列出的预期结果恰好是您要寻找的结果,那么将可以解决问题:

SELECT * FROM (
    SELECT CAST(GETDATE() AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -1, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -2, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -3, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -4, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -5, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -6, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -7, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
) AS the_table

结果:

Last_Seven_Days_Dates
---------------------
2018-07-05
2018-07-06
2018-07-07
2018-07-08
2018-07-09
2018-07-10
2018-07-11
2018-07-12

由于您说过要在临时表中使用它们,因此我更新了答案,使其成为子查询,使连接或执行操作变得容易一些。

另外,如果您需要在临时表中使用它,可以执行以下操作:

SELECT * INTO #TempTableName FROM (
    SELECT CAST(GETDATE() AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -1, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -2, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -3, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -4, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -5, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -6, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
    UNION
    SELECT CAST(DATEADD(DAY, -7, GETDATE()) AS DATE) AS Last_Seven_Days_Dates
)

答案 1 :(得分:3)

我将使用递归CTE:

with dates as (
      select cast(getdate() as date) as dte, 1 as cnt
      union all
      select dateadd(day, 1, dte), cnt + 1
      from dates
      where cnt < 7
     )
select dte
from dates;

答案 2 :(得分:3)

我使用以下内容生成日期序列

DECLARE @MinDate DATE = DATEADD(DAY, -7, GETDATE()),
        @MaxDate DATE = GETDATE();

SELECT  TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate)
FROM    sys.all_objects a;

您可以将其包装在函数中,如果需要使其可重用,则可以传入MinDate和MaxDate

答案 3 :(得分:1)

您可以使用

DATEADD(DAY, -7, getDate()) < [date_field]

根据您的查询

答案 4 :(得分:1)

select * from your_table
where  date_field>=dateadd(day,-7,cast(getdate() as date)) and date_field<cast(getdate() as date)