我有每行不同客户的发票的表。我想通过使用SQL(或SQL HANA)总量不仅所有同月和客户的发票,而且在另一列总从上个月去获得。
让:
Customer, Invoice Date(YearMonth), Amount
1, 201812, 12
1, 201811, 10
1, 201811, 15
1, 201811, 20
1, 201808, 12
1, 201807, 66
1, 201804, 12
1, 201801, 12
2, ...
...
=>
Customer, YearMonth Invoices, Total Month, Total Previous Month(YM -1 )
1, 201812, 12, 45
1, 201811, 45, 0
1, 201808, 12, 66
1, 201807, 66, 0
1, 201804, 12, 0
1, 201801, 12, 0
2, ..
注:我也有确切的发票日期,而不是只有YearMonth
当上HANA数据库执行以下SQLScript提供了所需的溶液
它包含一个子查询语句,并使用诸如SUM窗口函数与PARTITION BY子句
此外,我使用日期字符串和string to date conversion functions和add_months function
select distinct
Customer,
InvoiceDate,
SUM(Amount) OVER (PARTITION BY Customer, InvoiceDate) as TotalCurrent,
(
select sum(i.Amount)
from Invoices i
where i.Customer = j.Customer and i.InvoiceDate = TO_CHAR( add_months(TO_DATE(concat(j.InvoiceDate,'01')), -1) ,'YYYYMM')
) as PrevTotal
from Invoices j