如何在sql中选择表中行号数据的最大值?

时间:2016-09-23 11:43:30

标签: sql sql-server

我有这样的数据,

|   ID  |   Client  |   Some_Value  |   Row_No  |
|   1   |   HP      |   123         |   1   |
|   1   |   HP      |   1245        |   2   |
|   1   |   Dell    |   123445      |   3   |
|   2   |   HP      |   111         |   1   |
|   2   |   HP      |   223         |   2   |
|   3   |   Dell    |   34          |   1   |
|   3   |   Dell    |   5563        |   2   |

我需要像这样的输出,

|   ID  |   Client  |   Some_Value  |   Row_No  |
|   1   |   Dell    |   123445      |   3       |
|   2   |   HP      |   223         |   2       |
|   3   |   Dell    |   5563        |   2       |

请考虑我是初学者并向我解释逻辑。

1 个答案:

答案 0 :(得分:2)

USE Row_NUMBER()分区BY

;With T AS
(
    SELECT
        ID,
        Client,
        Some_Value,
        Row_No,
        Row_NUMBER() OVER(Partition BY ID Order BY Row_No Desc) AS PartNo
    FROM TableName
)
SELECT
    ID,
    Client,
    Some_Value,
    Row_No
FROM T
WHERE T.PartNo=1

更新声明示例:

;With T AS
(
    SELECT
        ID,
        Client,
        Some_Value,
        Row_No,
        Row_NUMBER() OVER(Partition BY ID Order BY Row_No Desc) AS PartNo
    FROM TableName
)
Update TableName
SET Name=T.Name
FROM T
WHERE T.PartNo=1 
AND TableName.Id=T.Id