0

我有这个 SQL Fiddle

当按 sequence_number 字段排序时,这些记录需要根据以下逻辑进行分组并赋予 row_number: 以下行类型不为 0 的所有记录都属于同一组。

例如,从提供的 SQL 小提琴中,

序号 0,1 和 2 属于同一组,序号 3 和 4 属于另一组。基本上,最多为 0 行类型的任何行都是单个组的一部分。我试图返回的数据将如下所示:

GROUP    LINE_TYPE    SEQUENCE_NUMBER    PRODUCT
------------------------------------------------
1        0            0                  REM322
1        6            1                  Discount
1        7            2                  Loyalty Discount
2        0            3                  RGM32
2        6            4                  Discount

另一种重新表述我所追求的方法是,当按序列号排序时,组号会在它为 0 时发生变化。

我一直在绞尽脑汁想如何使用分区/滞后甚至自连接来做到这一点,但遇到了麻烦。

任何帮助表示赞赏。

4

2 回答 2

1

如果 line_type 为 0,则将列值设置为 1,然后计算运行总和(使用 SUM 作为分析函数)。

select sum(case when line_type  = 0 then 1 
                else 0 end
          ) over (order by sequence_number) as grp,
       line_type,
       sequence_number,
       product
from ret_trand
order by sequence_number;

演示

于 2013-11-15T04:09:11.470 回答
0

进行分组的另一种方法是使用分层查询和CONNECT_BY_ROOT

SELECT CONNECT_BY_ROOT sequence_number AS first_in_sequence,
       line_type,
       sequence_number,
       product
FROM   ret_trand
START WITH
       line_type = 0
CONNECT BY
       (    sequence_number - 1 = PRIOR sequence_number
        AND line_type <> 0)
ORDER SIBLINGS BY
       sequence_number;

SQLFIDDLE

这将通过组的初始序列号来识别组。

如果要将其更改为组的顺序排名,则可以使用DENSE_RANK以下方法:

WITH first_in_sequences AS
(
  SELECT CONNECT_BY_ROOT sequence_number AS first_in_sequence,
         line_type,
         sequence_number,
         product
  FROM   ret_trand
  START WITH
         line_type = 0
  CONNECT BY
         (    sequence_number - 1 = PRIOR sequence_number
          AND line_type <> 0)
  ORDER SIBLINGS BY
         sequence_number
)
SELECT DENSE_RANK() OVER ( ORDER BY first_in_sequence ) AS "group",
       line_type,
       sequence_number,
       product
FROM   first_in_sequences;

SQLFIDDLE

于 2013-11-15T08:57:03.907 回答