sql用于使用最近日期

时间:2017-04-17 17:10:02

标签: sql sql-server

我已经搜索了其他几个SO问题,但我似乎仍然无法获得正确的结果。我希望根据Document获取CaseId表中的所有记录并使用最新的Status。我有两张桌子:

文件:

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

3 个答案:

答案 0 :(得分: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)

我认为这至少是一种方法。

根据AuditLog表中的Date Created列,您需要的是最新行的Status值。

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的价值不应该是"草案"?

答案 2 :(得分:0)

您可以将Common Table ExpressionROW_NUMBER一起使用,以便为AuditLog表的记录划分优先顺序。然后加入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