按特定行

时间:2015-09-01 01:35:48

标签: sql sap partitioning hana

我们拥有的是一张按日期和时间排序的表格:

date       | time        | amount | type
-----------+-------------+--------+-------
11/09/2014 | 11:13:03 AM | 1      | USE
11/09/2014 | 11:14:03 AM | 2      | USE
11/09/2014 | 12:13:03 AM | 10     | BUY
11/09/2014 | 12:15:03 AM | 1      | USE
11/09/2014 | 12:17:03 AM | 3      | USE
11/09/2014 | 12:18:03 AM | 1      | USE
11/09/2014 | 12:19:03 AM | 4      | USE
11/09/2014 | 13:13:03 AM | 15     | BUY
11/09/2014 | 14:13:03 AM | 1      | USE

我们希望在每次买入交易之间建立越来越多的USE交易。即我们想要得到一个这样的表:

date       | time        | amount | type
-----------+-------------+--------+-------
11/09/2014 | 11:13:03 AM | 1      | USE
11/09/2014 | 11:14:03 AM | 3      | USE
11/09/2014 | 12:13:03 AM | 10     | BUY
11/09/2014 | 12:15:03 AM | 1      | USE
11/09/2014 | 12:17:03 AM | 4      | USE
11/09/2014 | 12:18:03 AM | 5      | USE
11/09/2014 | 12:19:03 AM | 9      | USE
11/09/2014 | 13:13:03 AM | 15     | BUY
11/09/2014 | 14:13:03 AM | 1      | USE

您会看到每个 USE 交易中的金额是旧值和前一个 USE 交易中的值的总和。并且在每次购买交易后重置。

通过 BUY / USE 进行分区只会创建两个分区,因此它们的总和不是我们想要的。我们希望在每次购买交易时进行分区。

Afer花了一天时间试图解决这个问题,我想问一下如何在SQL中做到这一点,是否有可能?我们正在使用SAP HANA,以防万一。

1 个答案:

答案 0 :(得分:0)

You need to identify groups that end in "USE". One method is to do a cumulative reverse sum of "USE" values. Then do a cumulative sum, partitioned on this group.

I don't have access to SAP Hana, but this is standard SQL:

select t.*,
       sum(amount) over (partition by grp order by date, time) as cume_amount
from (select t.*,
             sum(case when type = 'BUY' then 1 else 0 end) over (order by date desc, time desc) as grp
      from table t
     )  t