Row_number over partition并找到max rn值

时间:2017-08-30 14:01:10

标签: sql sql-server select

我从下表开始:

+---+-----+---------+----------+----------+-------------+
| 1 | ID  | OrderNO | PartCode | Quantity | DateEntered |
| 2 | 417 | 2144    | 44917    | 100      | 40773       |
| 3 | 418 | 7235    | 11762    | 5        | 40773       |
| 4 | 419 | 9999    | 60657    | 100      | 40773       |
| 5 | 420 | 9999    | 60657    | 90       | 40774       |
+---+-----+---------+----------+----------+-------------+

到此:

+---+---------+----------+----------+-------------+----+
| 1 | OrderNO | PartCode | Quantity | DateEntered | rn |
| 2 | 2144    | 44917    | 100      | 40773       | 1  |
| 3 | 7235    | 11762    | 5        | 40773       | 1  |
| 4 | 9999    | 60657    | 100      | 40773       | 1  |
| 5 | 9999    | 60657    | 90       | 40774       | 2  |
+---+---------+----------+----------+-------------+----+

使用此answer的查询。

select OrderNO,PartCode,Quantity,row_number() over(partition by OrderNO order by DateEntered desc) as rn
from YourTable) as T

现在,我正在尝试添加一个字段" rn_max",shich是最大的""每个OrderNO得到以下结果:

+---+---------+----------+----------+-------------+----+--------+
| 1 | OrderNO | PartCode | Quantity | DateEntered | rn | rn_max |
| 2 | 2144    | 44917    | 100      | 40773       | 1  | 1      |
| 3 | 7235    | 11762    | 5        | 40773       | 1  | 1      |
| 4 | 9999    | 60657    | 100      | 40773       | 1  | 2      |
| 5 | 9999    | 60657    | 90       | 40774       | 2  | 2      |
+---+---------+----------+----------+-------------+----+--------+

我可以使用查询

计算每个OrderNO的最大值
SELECT OrderNO,MAX(rn) AS 'rn_max'
FROM (
select OrderNO,PartCode,Quantity,row_number() over(partition by OrderNO order by DateEntered desc) as rn
from YourTable
) T
Group by OrderNO

然后使用YourTable的左连接。 是否有最短的方法来计算具有相同OderNo的行?我已经尝试在查询中添加row_number() over(partition by OrderNO) as rn_max,但我需要编写一个order by子句。

2 个答案:

答案 0 :(得分:1)

使用max窗口功能。

SELECT T.*,MAX(rn) OVER(PARTITION BY OrderNo) AS 'rn_max'
FROM (
select OrderNO,PartCode,Quantity,row_number() over(partition by OrderNO order by DateEntered desc) as rn
from YourTable
) T

答案 1 :(得分:1)

你可以试试这个。 基本上,您在分区行上使用max()聚合来获取rn_max

select *, max(rn) over(partition by OrderNO)  as rn_max
FROM (
select OrderNO,PartCode,Quantity,row_number() over(partition by OrderNO order by DateEntered desc) as rn
from YourTable
) T