您好,对于 SQL 非常陌生,并且正在处理非常复杂的数据。我正在尝试根据剩余数量来识别篮子。当值减少时,我的 ID 号应该保持不变,但当它增加时,它应该更改为新的 ID 号(预期列)
select id, rem_material
DENSE_RANK() over (Partition by id Order by rem_material DESC ) as ExpectedID
from table
WHERE source ='area 5' and rem_material > 0
提供ID | 篮# | 剩余 | 预计ID |
---|---|---|---|
2150 | 1 | 5400 | 1 |
2151 | 1 | 2000 | 1 |
2152 | 1 | 1000 | 1 |
2153 | 1 | 0 | 1 |
2154 | 5 | 3400 | 2 |
2155 | 5 | 2050 | 2 |
2156 | 5 | 1010 | 2 |
2157 | 5 | 0 | 2 |
2158 | 1 | 4400 | 3 |
2159 | 1 | 3050 | 3 |
2160 | 1 | 1500 | 3 |
2161 | 1 | 1 | 3 |
2162 | 1 | 6000 | 4 |
2163 | 1 | 5000 | 4 |
2164 | 1 | 4500 | 4 |
2165 | 1 | 10 | 4 |
您似乎想在剩余数量增加时分配一个新的购物篮 ID。您可以使用 LAG 窗口函数将当前行的 rem_material 与前一行的值进行比较来实现此目的。如果当前值大于前一个值,则增加购物篮 ID;否则,您将保留相同的购物篮 ID。
示例代码:
WITH BasketCTE AS (
SELECT
id,
rem_material,
LAG(rem_material, 1, 0) OVER (ORDER BY id) AS prev_rem_material
FROM
YourTable
WHERE
source = 'area 5' AND rem_material > 0
)
SELECT
id,
rem_material,
SUM(CASE WHEN rem_material > prev_rem_material THEN 1 ELSE 0 END)
OVER (ORDER BY id) AS ExpectedID
FROM
BasketCTE;