sql - 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 子句中。
解决方案
只需使用窗口函数。我想你想要:
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
推荐阅读
- python - 用于连接 psycopg2 postgresql 的 python 文件
- excel - 在 Excel VBA 中设置对 Outlook 365 文件夹的引用
- javascript - 第二个 onclick 事件不起作用(首先做一些更改,第二个需要撤消它们)
- date - 如何使用时刻将字符串日期转换为 unix 格式
- php - 在没有关闭模式的情况下替换后刷新模式窗口中的图像
- r - 在互联网断开的机器上安装存储库时如何绕过 repos 错误?
- python - 蟒蛇 | 在字典中添加 2 个相同的键
- ruby-on-rails - 在rails中拆分字符串并附加单引号
- apache-spark - Hadoop CLI 命令获取使用的总内存等,如 8088 上的 Hadoop Web UI 中所示
- asp.net-core - 从所有会话中注销 IdentityServer4