首页 > 解决方案 > SQL 从属性每月重复的日期范围中查找最旧的日期

问题描述

需要帮助从表中隔离最旧的日期,其中以下属性:[进程 id]、[跟踪 id]、[bp] 在前几个月中是相同的。

我每月运行一次侦察报告。需要确定本月 Recon Report 中的记录是否出现在前几个月。如果记录出现在以前的报告中,我需要确定问题已打开的最早日期,以便我可以识别拖欠。上次运行报告的时间是 2020 年 6 月 31 日,但该问题在过去三个月内一直存在。

在此处输入图像描述

这是我希望看到的结果。

在此处输入图像描述

下面是他们询问我正在运行的问题。

declare @date  datetime
set @date= '6/30/2020'
select
    DATEDIFF(d,date, @date) as [Number of days outstanding],
    [Business Profile Name], 
    [Unit], 
    [Tracking ID], 
    [Owner], 
    [Issue]
from 
    [Recon_Report] 
where 
    concat ([process id],[tracking id],[bp]) in 
    (
        select 
            (concat ([process id],[tracking id],[bp]))
        from 
            [Recon_Report] 
        where 
            date = @date
    )
and date < @date
order by  [process id],[tracking id],[bp], Date asc

我尝试将此添加到查询中:

min(DATEDIFF(d,date, @date))

但我收到一条错误消息:

消息 8120,级别 16,状态 1,第 19 行列“Recon_Report.Date”在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

标签: sqlsql-server

解决方案


只需使用窗口函数。我想你想要:

select DATEDIFF(d,date, @date) as [Number of days outstanding],
       rr.*
from (select rr.*,
             max(case when date = @date then 1 else 0 end) over (partition by [process id], [tracking id], [bp]) as on_date,
             dense_rank() over (partition by [process id], [tracking id], [bp] order by date) as seqnum
      from Recon_Report rr
      where date <= @date
     ) rr
where seqnum = 1
order by  [process id], [tracking id], [bp], Date asc

推荐阅读