SQL根据两列的最大值选择所有列

时间:2013-09-16 10:39:00

标签: sql-server

我有一张这样的表

PkReferencesID    FkReferencesID   DocID    FKHRSEmployeeID  AssignedDate  AssignedTime  FKActivityID
40855             NULL             8530     13               13920625      0829          1
40856             40855            8530     438              13920625      0829          1
40857             40856            8530     13               13920625      0829          2
40858             40857            8530     438              13920625      0830          1
40859             40858            8530     NULL             13920625      0830          1
NULL              NULL             NULL     NULL             NULL          NULL          NULL 

如何为每个FKHRSEmployeeID选择DocID = 8530和FKActivityID = 1以及Maximum AssignedDate和Maximum AssignedTime的行?

注意:每个FKHRSEmployeeID

的结果应该是一行

任何帮助都会得到满足。谢谢

结果必须像这样

PkReferencesID FkReferencesID DocID FKHRSEmployeeID AssignedDate AssignedTime FKActivityID

40855 NULL 8530 13 13920625 0829 1 40858 40857 8530 438 13920625 0830 1

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by FKHRSEmployeeID
                                order by AssignedDate desc, AssignedTime desc
                               ) as seqnum
      from t
      where DocID = 8530 and FKActivityID = 1 
     ) t
where seqnum = 1

答案 1 :(得分:0)

查询2将检索您要求的信息:

Query1:此查询获取每位员工的最大分配日期/时间。

SELECT FKHRSEmployeeID, MAX(AssignedDate & AssignedTime)
FROM Table
WHERE T.DocID=8530 
  AND T.FKActivityID=1
GROUP BY FKHRSEmployeeID;

Query2:此查询使用前一个查询仅检索匹配的记录。

SELECT T.*
FROM Table AS T 
  INNER JOIN Query1 AS Q 
    ON (T.Date=LEFT(Q.MaxDateTime,8)) 
    AND (T.Time=RIGHT(Q.MaxDateTime,4)) 
    AND (T.FKHRSEmployeeID=Q.FKHRSEmployeeID)
WHERE T.DocID=8530 
  AND T.FKActivityID=1;

除非FKHRSEmployeeID / AssignedDate / AssignedTime组合在表中是唯一的,否则此查询本身并不保证每个员工只能获得一条记录。您可以通过基于这些列创建唯一索引来确保这一点。