2014-06-21 64 views
2

我有TSQL - 如何讓多個列

EMPLOYEE_CODE, 
ENTITLEMENT_CODE, 
TRANS_DATE, 
UNIQUE_ID, 
HOURS. 

我需要獲得最大TRANS_DATE的小時的EMPLOYEE_CODEENTITLEMENT_CODE每個組合表的MAX但有可能會有多個occurances的最大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 

任何幫助非常讚賞。

回答

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 
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

+0

這工作得很好哈姆雷特。我之前沒有使用CTE,所以我會多研究一下,以提高理解度,但查詢返回了我的預期。感謝您的幫助。 – user3762308

-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 
+1

這工作良好Vignesh並返回了我的預期。我不確定這是否比發佈的CTE解決方案有優勢。感謝您的幫助。 – user3762308

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_CODE指數和ENTITLEMENT_CODE(複合)爲此有效地工作。