sql窗口函数基于行的开始标志和结束标志

时间:2016-09-09 20:20:44

标签: sql oracle teradata window-functions

我表中的数据目前有如下数据。 我希望使用窗口函数基于child_startchild end列的数字行。

数据样本

LoadNumber |DispatchNumber|ChildLoadStart|ChildLoadEnd  |
---------------------------------------------------------
123        | A            |1             |1             |
---------------------------------------------------------
123        |B             |1             |0             |
---------------------------------------------------------
123        |C             |0             |0             |
---------------------------------------------------------
123        |D             |0             |1             |
---------------------------------------------------------

在负载123的上述数据中,我有两个子负载,即,分派A是一个子负载,分派B,C,D形成一个多子负载。 所以我需要为每个子载荷编号如下; 结果应该如下所示。有人可以帮我这个吗?

LoadNumber |DispatchNumber|ChildLoadStart|ChildLoadEnd  |Order         |
-----------------------------------------------------------------------
123        | A            |1             |1             |1             |
------------------------------------------------------------------------
123        |B             |1             |0             |1             |
------------------------------------------------------------------------
123        |C             |0             |0             |2             |
------------------------------------------------------------------------
123        |D             |0             |1             |3             |
------------------------------------------------------------------------

2 个答案:

答案 0 :(得分:1)

如果DispatchNumber可用于订购数据:

ROW_NUMBER()
OVER (PARTITION BY LoadNumber
      ORDER BY DispatchNumber
      RESET WHEN ChildLoadStart = 1) 

答案 1 :(得分:0)

@dnoeth提出的reset when条款可能正是这里所需要的。但是我对Teradata并不熟悉,所以下面是Oracle的替代品,也许这对某人有用。

首先使用累积总和将数据划分为多个组,然后在grp中使用此列(partition by clause)作为row_number()

select loadnumber, dispatchnumber, childloadstart, childloadend, 
       row_number() over (partition by loadnumber, grp order by dispatchnumber) as "ORDER"
  from (
    select data.*,
           sum(childloadstart) over (partition by loadnumber order by dispatchnumber) grp
      from data )

测试数据和输出:

create table data (LoadNumber number(4), DispatchNumber varchar2(2), 
                   ChildLoadStart number(1), ChildLoadEnd number(1));

insert into data values (123, 'A', 1, 1);
insert into data values (123, 'B', 1, 0);
insert into data values (123, 'C', 0, 0);
insert into data values (123, 'D', 0, 1);

LOADNUMBER DISPATCHNUMBER CHILDLOADSTART CHILDLOADEND      ORDER
---------- -------------- -------------- ------------ ----------
       123 A                           1            1          1
       123 B                           1            0          1
       123 C                           0            0          2
       123 D                           0            1          3