代码之家  ›  专栏  ›  技术社区  ›  BIReportGuy

SQL上一个日期记录

  •  -1
  • BIReportGuy  · 技术社区  · 8 年前

    以下是数据库中的日期,它们可能是每个月的不同日期(不总是在1号发布)。因此,我需要提取最新(最大值)(2017-07-03和之前的日期2017-06-01)

    filedate
    2017-05-01
    2017-06-01
    2017-07-03
    

    declare @filedate date = '2017-07-03'
    
    select distinct max(filedate) filedate
    from Table
    where filedate = @filedate
    order by filedate asc
    
    
    select filedate
    from Table
    where filedate < (select min(@filedate) from Table)
    group by filedate
    

    结果是:

    filedate (from the first query)
    2017-07-03
    
    filedate (from the second query)
    2017-05-01
    2017-06-01
    
    4 回复  |  直到 8 年前
        1
  •  1
  •   CuriousKid    8 年前

    这是一个神奇的问题:

    SELECT DISTINCT TOP 2 filedate
    FROM TABLE
    ORDER BY filedate DESC
    
        2
  •  0
  •   Chuck    8 年前

    选择前两个怎么样?这样地:

    select top 2 filedate
    from Table
    order by filedate desc
    
        3
  •  0
  •   Vijunav Vastivch    8 年前

    select max(filedate)from
    (select '2017-05-01' as filedate union all
    select '2017-06-01' union all
    select '2017-04-10' union all
    select '2017-07-03') as a where filedate<
    
    (select max(filedate)from
    (select '2017-05-01' as filedate union all
    select '2017-06-01' union all
    select '2017-04-10' union all
    select '2017-07-03') as a limit 1)
    
    union ALL
    
    select max(filedate)from
    (select '2017-05-01' as filedate union all
    select '2017-06-01' union all
    select '2017-04-10' union all
    select '2017-07-03') as a 
    

    结果:

    2017-06-01
    2017-07-03
    

    您只需将示例数据替换为表名,如下所示:

    select max(filedate)from
    (select filedate from yourtable) as a where filedate<
    
    (select max(filedate)from
    (select filedate from yourtable) as a limit 1)
    
    union ALL
    
    select max(filedate)from
    (select filedate from yourtable) as a 
    
        4
  •  0
  •   Chuck    8 年前

    @CuriousKid. ..这是我所做的,使这项工作。

    declare @filedate date = (select max(filedate) from Table)  --'2017-07-03'
    
    select distinct top 1 filedate as PriorDate
    from Table
    where filedate <> @filedate
    order by filedate desc