TSQL - 如何获得多列的MAX

时间:2014-06-21 07:18:43

标签: sql-server tsql max multiple-columns

我有一张表

EMPLOYEE_CODE, 
ENTITLEMENT_CODE, 
TRANS_DATE, 
UNIQUE_ID, 
HOURS. 

我需要为TRANS_DATEEMPLOYEE_CODE的每个组合获得最多ENTITLEMENT_CODE的HOURS,但有可能会出现多次TRANS_DATE的最大值,因此我需要进一步细化查询以获取UNIQUE_ID的最大值,从而获得返回的此特定行的HOURS。我尝试了各种方法,但我可以得到部分查询但不是整个事情。

所以我可能有类似的东西:

EMPLOYEE_CODE,  ENTITLEMENT_CODE,   TRANS_DATE, UNIQUE_ID,  HOURS.
-----------------------------------------------------------------
2305            ANNL                04/15/2014  28547       15.55
2305            ANNL                04/15/2014  28622       16.83
2305            ANNL                04/15/2014  28223       18.62
2305            ANNL                04/08/2014  28111       12.22
2305            SICK                04/12/2014  28150       14.47
2305            SICK                04/12/2014  28162       12.44
2305            SICK                03/11/2014  28062       18.66 

所以这需要返回

16.83 for 2305 ANNL 
12.44 for 2305 SICK

任何帮助都非常感激。

4 个答案:

答案 0 :(得分:4)

试试这个:

;WITH CTE
AS
(
    SELECT
      *,
      ROW_NUMBER() OVER (PARTITION BY EMPLOYEE_CODE, ENTITLEMENT_CODE
                         ORDER BY TRANS_DATE DESC, UNIQUE_ID DESC) rn
    FROM tbl
)
SELECT 
  EMPLOYEE_CODE, 
  ENTITLEMENT_CODE, 
  HOURS
FROM CTE
WHERE rn = 1

<强> SQL FIFFLE DEMO

答案 1 :(得分:0)

尝试将row_number()partition by clause

一起使用
select * from
(
select *,rn=row_number()over(partition by ENTITLEMENT_CODE order by UNIQUE_ID desc)
from table
)x
where x.rn=1

答案 2 :(得分:0)

如果您更喜欢使用相关子查询:

SELECT HOURS, EMPLOYEE_CODE, ENTITLEMENT_CODE
FROM mytable T1
WHERE NOT EXISTS
(
    SELECT *
    FROM mytable T2
    WHERE  T2.EMPLOYEE_CODE    = T1.EMPLOYEE_CODE
      AND  T2.ENTITLEMENT_CODE = T1.ENTITLEMENT_CODE
      AND (T2.TRANS_DATE > T1.TRANS_DATE
        OR T2.TRANS_DATE = T1.TRANS_DATE AND T2.UNIQUE_ID > T1.UNIQUE_ID)
)

您最好具有超过EMPLOYEE_CODEENTITLEMENT_CODE的索引(合成),以便有效地工作。

答案 3 :(得分:-1)

可能是这样的东西

 Select T.* From Table1 T JOIN
   ( Select Max(S.UNIQUE_ID) MaxUniq,S.EMPLOYEE_CODE,S.ENTITLEMENT_CODE
     From Table1 S Join
        ( Select T1.EMPLOYEE_CODE,T1.ENTITLEMENT_CODE,Max(T1.TRANS_DATE) As MaxDate
          From Table1 T1 Group By T1.EMPLOYEE_CODE,T1.ENTITLEMENT_CODE
        ) JR On S.TRANS_DATE = JR.MaxDate AND S.EMPLOYEE_CODE = JR.EMPLOYEE_CODE AND S.ENTITLEMENT_CODE = JR.ENTITLEMENT_CODE
         Group By S.EMPLOYEE_CODE,S.ENTITLEMENT_CODE
 )R ON T.UNIQUE_ID = R.MaxUniq 

<强> Fiddle Demo

输出将是:


EMPLOYEE_CODE   ENTITLEMENT_CODE    TRANS_DATE  UNIQUE_ID   HOURS
2305            ANNL                2014-04-15  28622       16.83
2305            SICK                2014-04-12  28162       12.44