【问题标题】:From a series of invoices with date, how could I aggregate them by invoice month and previous invoice month?从一系列带有日期的发票中,我如何按发票月份和上一个发票月份汇总它们?
【发布时间】:2019-02-06 19:17:15
【问题描述】:

我有一张表格,每行都有不同客户的发票。 我想通过使用 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, ..

注意:我也有确切的发票日期,而不仅仅是年月

【问题讨论】:

    标签: sql hana


    【解决方案1】:

    在 HANA 数据库上执行时,遵循 SQLScript 提供了所需的解决方案

    它包括一个子选择语句和使用 SUM 等窗口函数和 Partition By 子句

    另外,我使用日期字符串和string to date conversion functionsadd_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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-18
      • 2021-03-31
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      相关资源
      最近更新 更多