当二进制列等于0

时间:2019-10-02 02:30:05

标签: sql teradata

我在下面有一个样本表。我试图创建一个在Flag等于0时没有递归表的情况下重置的计数。

Animal  Order  Flag
Cat     1      0
Cat     2      0
Cat     3      1
cat     4      1
cat     5      0
cat     6      1
cat     7      1
Dog     1      0
Dog     2      1
Dog     3      1
Dog     4      1
Dog     5      0
Dog     6      0
Dog     7      1

我尝试了各种row_numberrankdense_rank,但没有什么让我接近。我得到的最接近的方法是使用下面的滞后方法,但是它只能计数到2,并且需要能够无限期地计数。

滞后: MAX(flag ) OVER(PARTITION BY 1 ORDER BY Order ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)

所需的输出

Animal  Order  Flag  Count
Cat     1      0     0
Cat     2      0     0
Cat     3      1     1
cat     4      1     2
cat     5      0     0
cat     6      1     1
cat     7      1     2
Dog     1      0     0
Dog     2      1     1
Dog     3      1     2
Dog     4      1     3
Dog     5      0     0
Dog     6      0     0
Dog     7      1     1

2 个答案:

答案 0 :(得分:1)

您还可以使用RESET WHEN(它是Teradata扩展名)来进行此操作:

SELECT animal, order, flag,
  SUM(flag) OVER(
    PARTITION BY animal -- Group by animals
    ORDER BY order
    RESET WHEN flag = 0 -- Reset count to 0
    ROWS UNBOUNDED PRECEDING -- Cumulative count
  ) AS count 
FROM mytable

我没有要测试的TD系统,请尝试一下,让我知道。

Example

答案 1 :(得分:0)

为每行分配grouping。然后使用row_number()

select t.*,
       (case when flag = 0 then 0
             else row_number() over (partition by animal, grouping order by order) - 1
        end) as count
from (select t.*,
             sum(case when flag = 0 then 1 else 0 end) over
                 (partition by animal
                  order by order
                  rows between unbounded preceding and current row
                 ) as grouping
      from t
     ) t

- 1是因为1的每个序列还包括前一个0。您也可以将其表示为:

             else row_number() over (partition by animal, grouping, flag order by order)

所以只有1个在组中。