根据上次更新日期 + null 计算记录数

Count number of records based on last updated date + null

遇到我认为很简单的问题。我们的系统试图计算没有标题的项目数量,按 'last_updated_date'.

跟踪记录
id    work_item      title         last_updated_date  
1     task1          ProjectA      2020-03-25 20:20:01.111
2     task2          ProjectA      2020-03-25 20:20:01.111
3     task3                        2020-03-25 20:20:01.111
4     task4          ProjectB      2020-03-25 20:20:01.111
5     task5          ProjectC      2020-03-25 20:20:01.111

如您所见,我需要查看哪些工作项没有项目。如果我要查看 'task1' 的历史记录,我会看到如下内容:

select work_item, last_updated_date, project
from table
where work_item = 'task1'

这将输出:

work_item      last_updated_date          title
task1          2020-03-25 20:20:01.111    ProjectA
task1          2020-03-17 20:20:01.111    NULL
task1          2020-03-12 20:20:01.111    NULL

基于此,我可以看到 task1 在 2020-03-25 上分配了一个标题。我需要知道的是,整个数据集中有多少工作项没有分配项目。所以我想使用最后更新日期检查所有记录并检查最新的 last_updated_date 以查看标题是否为空。我尝试了以下方法,但我认为我错误地使用了 MAX and/or 组?我正在取回已分配标题的记录,这让我认为它正在检查整个 last_updated_date 列的最大值,而不是其中的每条记录。

select id, title, MAX(last_updated_date) as "latest_timestamp"
FROM table
WHERE title is null
group by id, title

我希望看到的是只有任务 3 显示为需要分配标题。

一个选项使用子查询来过滤每个项目的最新记录。然后你可以数一数有多少人没有标题:

select count(*)
from mytable t
where 
    last_updated_date = (
        select max(t1.last_updated_date) 
        from mytable t1 
        where t1.work_item = t.work_item
    )
    and title is null

您还可以使用 window 函数:

select count(*)
from (
    select t.*, 
        row_number() over(partition by work_item order by last_updated_date desc) rn
    from mytable t
) t
where rn = 1 and title is null