如何用行写选​​择最大值?

时间:2018-02-01 11:14:17

标签: sql sql-server

我有一张表Final_Table_2,我使用了ROW_NUMBER() OVER(PARTITION BY mrID ORDER BY mrID ) AS ID

如何在没有循环的情况下为每个mrID号码(例如:9998,9999)选择max(ID)行?

ID  mrID  mrSEQUENCE mrNEWFIELDVALUE mrTIMESTAMP    mrUSERID
1   9998    35844      Closed        NULL           abacki
2   9998    36045      Closed        NULL           babacki
3   9998    36046      Closed        NULL           Return
4   9998    36626      Closed        NULL           Return
5   9998    36381      Resolved      NULL           cabacki
6   9998    36275      Closed        NULL           cabacki

1   9999    35847       Closed         NULL         kabacki
2   9999    35848       Closed         NULL         kabacki
3   9999    35849       Closed         NULL         kabacki

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT * 
FROM(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY mrID ORDER BY ID DESC) AS RN
    FROM Your_Table
    )D
WHERE RN=1

答案 1 :(得分:1)

试试这个:

SELECT t.*
FROM Final_Table_2 t
WHERE NOT EXISTS(
    SELECT 'NEXT'
    FROM Final_Table_2 t2
    WHERE t2.mrID = t.mrID
    AND t2.ID > t.ID
)