2017-04-17 78 views
0

我已经搜索了几个其他的问题,但我仍然无法得到正确的结果。我想根据CaseId获得Document表中的所有记录,并获得最近的Status。我有两个表:SQL状态使用最近的日期

文件:

DocumentId | CaseId | Name 
---------------------------------------- 
2   |  23  | Document 1 
3   |  23  | Document 2 
4   |  24  | Document 3 

审计日志:

AuditLogId | Status | DocumentId | Date Created 
--------------------------------------------------------- 
10   | Active |  2  | 4/2/2017 
11   | Draft |  2  | 4/1/2017 
12   | Released |  2  | 4/3/2017 
13   | Draft |  3  | 4/17/2017 
14   | Draft |  4  | 4/17/2017 

所以对于CaseId: 23期望的结果将是:

Status | DocumentId | CaseId | Name 
---------------------------------------------- 
Released |  2  | 23 | Document 1 
Draft  |  3  | 23 | Document 2 

我有关闭该查询,但是这只是给了我最近的所有结果为CaseId 23,而不是由DocumentId分组:

Select s.Status, lh.* from LegalHold lh join(
    Select Status, LegalHoldId 
    FROM LegalHoldAuditLog 
    WHERE DateCreated = (select max(DateCreated) 
    from LegalHoldAuditLog)) s on lh.LegalHoldId = s.LegalHoldId 
    WHERE lh.CaseId = 23 
+1

没有为'DocumentId = 3'在'AuditLog'表只是一个记录,这个记录有'状态= Draft'。你如何在结果中拥有“主动”? –

+0

@GiorgosBetsos可能只是与DocumentId字段混淆。 –

+0

@GiorgosBetsos是的,我的错误,我已经更新了结果 – user2884789

回答

2

使用cross apply()得到最新Status为每个DocumentId

select d.*, al.Status 
from Document d 
    cross apply (
    select top 1 i.Status 
    from AuditLog i 
    where i.DocumentId = d.DocumentId 
    order by i.date_created desc 
    ) as al 
where d.CaseId = 23 

top with ties版本使用row_number()

select top 1 with ties d.*, al.Status 
from Document d 
    inner join AuditLog al 
    on d.DocumentId = al.DocumentId 
order by row_number() over (partition by al.DocumentId order by al.date_created desc) 
+1

顶部与领带是一个很好的! –

+0

@SqlZim与领带的顶部工作很好,但我没有改变啊在括号中的al与'partition by',否则它不起作用。请让我知道,如果这不是你的错误。 – user2884789

+0

@ user2884789是一个错字。更新 – SqlZim

0

我认为这将是这样做至少有一种方式。

根据AuditLog表中的“创建日期”列,您需要的只是最新一行中的状态值。

SELECT (SELECT TOP 1 Status 
     FROM AuditLog 
     WHERE AuditLog.DocumentId = Document.DocumentId 
     ORDER BY [Date Created] DESC), 
     DocumentId, CaseId, Name 
FROM Document 
WHERE CaseId = 23 

而不是文档2的值是“草稿”?

0

可以以优先AuditLog表的记录使用与ROW_NUMBER一个Common Table Expression。然后加入到Document表来获得期望的结果:

;WITH AuditLog_Rn AS (
    SELECT Status, DocumentId, 
      ROW_NUMBER() OVER (PARTITION BY DocumentId 
          ORDER BY [Date Created] DESC) AS rn 
    FROM AuditLog 
) 
SELECT d.DocumentId, d.CaseId, d.Name, al.Status 
FROM Document AS d 
JOIN AuditLog_Rn AS al ON d.DocumentId = al.DocumentId AND al.rn = 1