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

时间:2017-12-17 21:43:00

标签: sql sap hana

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

例如:输入:

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做的那样,如果存在任何其他逻辑,请帮助我!

1 个答案:

答案 0 :(得分:0)

for the solution of this requirement, I can suggest you to use a numbers table on HANA database. In the following part, I've shared the SQLScript codes in which I've used this numbers table function for creating the series of dates in a specific range

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

You see I used the numbers function "Numbers_Table" in the outer SELECT statement which creates the FROM part of the join clause

For simulating the COUNTs, I assume that a record cannot be CLOSED before it is OPENED so, when it is in OPEN status I add 1 to OPEN state count. While the record is closing, I add 1 to CLOSED state. But the trick here is, I use -1 for OPEN state for a closing item. SUM() aggregation function helps me to get the final row data

The output is as follows,

enter image description here