【问题标题】:Previous month difference and last year-end difference in oracle sqloracle sql上月差异和上年末差异
【发布时间】:2014-11-26 09:42:51
【问题描述】:

我需要编写一个查询来计算上月末和月末之间的差异以及去年年底和月末之间的差异。我在 sqlfiddle http://sqlfiddle.com/#!4/b9749 中创建了示例数据库 在我的数据库中,最重要的日期始终是月底,但正如您在示例中看到的那样,还有其他日期,但我不能使用这些日期的值。当我以 date ='2014-04-30' 为条件运行此查询时,结果应如下所示:

date        product    amount     last_month_diff     last_year_end_diff
2014-04-30       a1       350                -150                    650
2014-04-30       b1       123                -123                   1877

当我以 date ='2014-05-31' 为条件运行此查询时,结果应该是这样的

date        product    amount     last_month_diff     last_year_end_diff
2014-05-31       a1       400                 -50                    600
2014-05-31       b1       500                -377                   1500
2014-05-31       c1       200                   0                      0

当我以 date ='2014-06-30' 为条件运行此查询时,结果应该是这样的

date        product    amount     last_month_diff     last_year_end_diff
2014-06-30       b1       780                -280                   1220
2014-06-30       c1       100                 100                      0

起初我以为我使用分析函数(滞后),但我可能在两个月末之间有很多日期,我不知道如何达到预期的结果。

【问题讨论】:

    标签: oracle


    【解决方案1】:

    试试下面的方法。

    with input_date as (select to_date('2014-04-30', 'YYYY-MM-DD') d from dual),
    sot_tot as (select product, 
                       sum(case when extract(month from date_) = extract(month from d) then amount else 0end) amount,       
                       sum(case when extract(month from date_) = extract(month from last_day(add_months(d, -1))) then amount else 0 end) previous_month_amount
                from sot, input_date
                where date_ <= d
                group by product)
    
    select product, amount, previous_month_amount - amount as previos_month_diff
      from sot_tot
    

    我无法理解您所说的difference between last month-end and month-end and difference between last year-end and month-end. 是什么意思,但是解决方案与上面的解决方案非常相似,您可以使用 sum 和 case 组合来获得您想要的结果。

    【讨论】:

    • 谢谢。我通过在 case 表达式中添加空值而不是 0 来更改您的查询。有没有办法排除当前日期不存在的产品?例如,此结果中的产品“c1”? sqlfiddle.com/#!4/b9749/35
    • 尝试在你的where子句中控制它。可能像where amount is not null 这样的东西会做。
    猜你喜欢
    • 2019-08-31
    • 2021-07-18
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2020-12-23
    • 2011-12-18
    • 2022-10-07
    相关资源
    最近更新 更多