2017-04-17 86 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