基于flag变量break row_number()序列

时间:2017-10-19 12:14:51

标签: sql postgresql break rownum

希望找到一些东西。

我的数据如下所示

id  month flag
111 jan   1
111 feb   1
111 mar   1
111 apr   0
111 may   0
111 jun   1
222 jan   1
222 feb   1
222 mar   0
222 apr   0
222 may   0
222 jun   1

我在寻找输出

id  month flag order
111 jan   1    1
111 feb   1    2
111 mar   1    3
111 apr   0    1
111 may   0    2
111 jun   1    1
222 jan   1    1
222 feb   1    2
222 mar   0    1
222 apr   0    2
222 may   0    3
222 jun   1    1

我试过row_number(),但问题是我们无法打破序列并重新开始。在整体水平上,当标志变量从0变为1或从1变为0时,我需要分别从每个id开始计数

1 个答案:

答案 0 :(得分:1)

假设SQL Server,这是一个例子:

DECLARE @T table (id int, [month] char(3), flag bit)

INSERT INTO @T
VALUES
(111, 'jan', 1)
,(111, 'feb', 1)
,(111, 'mar', 1)
,(111, 'apr', 0)
,(111, 'may', 0)
,(111, 'jun', 1)
,(222, 'jan', 1)
,(222, 'feb', 1)
,(222, 'mar', 0)
,(222, 'apr', 0)
,(222, 'may', 0)
,(222, 'jun', 1)

SELECT
    id
    , [month]
    , flag
    , ROW_NUMBER() OVER (PARTITION BY id, section ORDER BY monthNum) [order]
FROM
    (
        SELECT
            id
            , [month]
            , monthNum
            , flag
            , SUM(CASE WHEN newValue = 1 THEN 1 ELSE 0 END) OVER (PARTITION BY id ORDER BY monthNum) section
        FROM
            (
                SELECT
                    id
                    , [month]
                    , monthNum
                    , flag
                    , CASE WHEN LAG(flag, 1, ABS(flag - 1)) OVER (PARTITION BY id ORDER BY monthNum) = flag THEN 0 ELSE 1 END newValue
                FROM
                    (
                        SELECT
                            id
                            , [month]
                            , MONTH(CAST('1 ' + [month] + ' 17' AS datetime)) monthNum
                            , flag
                        FROM @T
                    ) Q
            ) Q2
    ) Q3