添加下个月前几个月的数据,SAP HANA计算视图中的数据历史记录

问题描述 投票:0回答:1

历史化意味着我们将在接下来的几个月中显示前几个月的数据。

例如:输入:

ID  STATUS  YEAR MONTH
A   OPEN    2017-01
A   CLOSED  2017-03
B   OPEN    2017-01
B   Closed  2017-05

我的O / P:

YEAR MONTH     COUNT-OPEN                         COUNT-CLOSED
2017-01     2(both A & B OPEN)                      0
2017-02     2(FROM 201701)                          0
2017-03     2(from 2017-02)-1(A Closed now)=1   1
2017-04     1(from 201703)=1                    1(from prev month)
2017-05     1-1(b closed)=0                     1+1(b closed)=2

值是实际的o / p我刚刚写了公式,让你理解逻辑。我需要在上个月到下个月添加打开/关闭数据,是否可以在SAP HANA W / O中使用游标?正如我可以用Cursors做的那样,如果存在任何其他逻辑,请帮助我!

sql sap hana
1个回答
0
投票

为了解决这个问题,我建议你在HANA数据库上使用数字表。在下面的部分中,我已经共享了SQLScript代码,其中我使用了这个numbers table function来创建特定范围内的一系列日期

with input as (
    select
        id,
        status,
        year,
        cast(month as integer) month,
        case when status = 'OPEN' then 1 else -1 end as COUNT_OPEN,
        case when status = 'CLOSED' then 1 else 0 end as COUNT_CLOSED
    from Historization
)
SELECT 
    y.rownum as year,
    m.rownum as month,
    (select sum(COUNT_OPEN) from input where  year <= y.rownum and month <= m.rownum) as COUNT_OPEN,
    (select sum(COUNT_CLOSED) from input where  year <= y.rownum and month <= m.rownum) as COUNT_CLOSED
FROM Numbers_Table(2017) as y
CROSS JOIN Numbers_Table(12) as m
where y.rownum = 2017
order by y.rownum, m.rownum

您看到我在外部SELECT语句中使用了数字函数“Numbers_Table”,它创建了join子句的FROM部分

为了模拟COUNT,我假设一条记录在打开之前不能被禁止,所以当它处于OPEN状态时,我将1添加到OPEN状态计数。在记录结束时,我将1添加到CLOSED状态。但这里的诀窍是,我使用-1作为关闭项目的OPEN状态。 SUM()聚合函数帮助我获取最终的行数据

输出如下,

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.