窗口函数—为一组重复值分配组号的sql解决方案

xn1cxnb4  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(336)

我有一个表,表中列有customer、order、fruit和quantity,按customer和order排序。
我需要按顺序分配示例所需的组号值,从1开始,分配相同的值直到水果改变,然后为下一个水果增加1,当客户改变时重置回1。
我绞尽脑汁想出了一个解决方案,使用滞后,排名或行号窗口函数,但仍然难以捉摸。建议?!?!

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
k10s72fa

k10s72fa1#

它可以通过加窗求和和和滞后来实现:

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<>小提琴演示

相关问题