我如何获得场所的最新工作完成日期,而最近的工作也有空白的完成日期?

How do I get the latest job completed date for a premises that also has a blank completion date for a more recent job?

(精简)作业 table 具有以下字段:job.id、job.premises_id、job.completed_date

我需要知道 job.completed_date 为空的场所(工作已预订但尚未完成)输出必须包括该场所的 max(job.completed_date)(最多日期最近在该场所完成的工作。

我试过了:

SELECT job.premises_id
, job.jobid
,(SELECT MAX(job.completed_date) FROM job where job.completed_date IS NOT NULL) as 'last job'

FROM job

WHERE job.completed_date is null

示例数据将帮助您解决问题,但假设您可以为一个 jobid 设置多行,您需要在子查询中包含一个 correlation ; Max 已排除空值。

select j.premises_id, j.jobid, (
    select Max(j2.completed_date) 
      from job j2
      where j2.jobId = j.JobId
  ) as [last job]
from job j
where j.completed_date is null;

您可能还需要在关联中包含 premises_id。还要注意分隔符应该是方括号或双引号。

也许是带有分区聚合的 CTE?

WITH CTE AS(
    SELECT j.premises_id,
           j.jobid,
           j.completed_date,
           MAX(j.completed_date) OVER (PARTITION BY j.premises_id) AS MaxCompletedDate
    FROM dbo.job j)
SELECT premises_id,
       jobid,
       MaxCompletedDate
FROM CTE
WHERE completed_date IS NULL;