我正在尝试基于动态滞后函数获得估价,而我不会。 我有一个看起来像这样的表,我想要的是序列号产品的值,该值比我当前的序列号高1。
+--------+---------+--------+------------------------+----------+
| Client | Product | Ser_No | Product Ser_No+1 I get | Expected |
+--------+---------+--------+------------------------+----------+
| 1 | A | 1 | B | B |
+--------+---------+--------+------------------------+----------+
| 1 | B | 2 | C | C |
+--------+---------+--------+------------------------+----------+
| 1 | C | 3 | D | F |
+--------+---------+--------+------------------------+----------+
| 1 | D | 3 | E | F |
+--------+---------+--------+------------------------+----------+
| 1 | E | 3 | F | F |
+--------+---------+--------+------------------------+----------+
| 1 | F | 4 | null | null |
+--------+---------+--------+------------------------+----------+
| 2 | D | 1 | E | E |
+--------+---------+--------+------------------------+----------+
| 2 | E | 2 | F | G |
+--------+---------+--------+------------------------+----------+
| 2 | F | 2 | G | G |
+--------+---------+--------+------------------------+----------+
| 2 | G | 3 | H | H |
+--------+---------+--------+------------------------+----------+
| 2 | H | 4 | I | I |
+--------+---------+--------+------------------------+----------+
| 2 | I | 5 | null | null |
+--------+---------+--------+------------------------+----------+
我唯一能想到的就是Lag(product,1),但这并不是我现在想要的。有什么想法吗?
这就是我现在要做的:
LEAD(Product, 1) OVER(PARTITION BY Cliënt ORDER BY Ser_No ASC)
但是问题出在第3、4和8行。在这里,我需要的不是下一行的产品代码,而是下一个Ser_No的产品代码
答案 0 :(得分:1)
我可能会在这里使用lead
而不是lag
SELECT Client,
Product,
Ser_No,
LEAD(Product) OVER(PARTITION BY Client ORDER BY Ser_No) As [Product Ser_No+1]
FROM TableName
要使用Lag
,您需要order by Ser_No desc
。
有了这个新的编辑,我会这样:
WITH CTE AS
(
SELECT Client,
Product,
Ser_No,
DENSE_RANK() OVER(PARTITION BY Client ORDER BY Ser_No) As rnk
FROM TableName
)
SELECT Client,
Product,
Ser_No,
(
SELECT Product
FROM CTE t1
WHERE t1.Client = t0.Client
AND t1.Rnk = t0.Rnk + 1
) As [Product Ser_No+1]
FROM CTE t0