SQL给一组重复值分配组号的解决方法

SQL solution to assign a group number to a set of repeated values

我有一个 table,其中包含客户、订单、水果和数量列,按客户和订单排序。

我需要按顺序分配示例 Desired Group Number 值,从 1 开始,分配相同的值直到 Fruit 改变,然后为下一个 Fruit 递增 1,当 Customer 改变时重置回 1。

我绞尽脑汁想出一个使用 LAG、RANK 或 ROW_NUMBER window 函数的解决方案,但仍然感到困惑。建议?!?!

Customer Order Fruit   Qty  DESIRED GROUP NUMBER
-------- ----- -----   ---  --------------------
A        1     Apple.   5     1
A        2     Apple.   4     1
A        3     Apple.   6     1
A        4     Banana.  4     2
A        5     Orange.  1     3
A        6     Orange.  9     3
A        7     Apple.   9     4
A        8     Apple.   3     4
B        1     Banana.  6     1
B        2     Banana.  5     1
B        3     Apple.   4     2

可以用加窗的SUM和LAG来实现:

WITH cte_lag AS
(
  SELECT t.*, LAG(t.Fruit) OVER(PARTITION BY Customer ORDER BY "order") AS fruit_prev
  FROM t
) 
SELECT *,SUM( CASE WHEN fruit = COALESCE(fruit_prev,fruit) THEN 0 ELSE 1 END) 
            OVER(PARTITION BY Customer  ORDER BY "order") + 1 AS grp
FROM cte_lag
ORDER  BY customer, "order";

db<>fiddle demo