获取同一列的当前数据和上个月数据

时间:2019-11-06 13:58:01

标签: sql oracle date subquery

我正在比较Oracle SQL中11月(11)和10月(10)的AMOUNTPROJECT_ID的值。

我尝试了子查询,但是AMOUNT_LAST_MONTH显示了相同的结果。

select 
    PROJECT_ID, 
    sum(AMOUNT), 
    ( 
        select sum(amount) 
        from APPS.pa_draft_revenue_items
        where 
            to_char(LAST_UPDATE_DATE,'MM')='10' 
            AND to_char(LAST_UPDATE_DATE,'YYYY')='2019'
    ) AMOUNT_LAST_MONTH
from 
    APPS.pa_draft_revenue_items 
where 
    PROJECT_ID IN (
        select PROJECT_ID 
        from APPS.pa_draft_revenue_items
        where 
            to_char(LAST_UPDATE_DATE,'MM')='11' 
            AND to_char(LAST_UPDATE_DATE,'YYYY')='2019' 
    ) 
GROUP by PROJECT_ID, amount ;

我希望AMOUNT_LAST_MONTH具有不同的值。

enter image description here

3 个答案:

答案 0 :(得分:1)

如果我正确地关注了您,则可以通过使用条件聚合来大大简化您的查询:

select 
    project_id, 
    sum(case when extract(month from last_update_date) = 10 then amount end) amount_last_month, 
    sum(case when extract(month from last_update_date) = 11 then amount end) amount_this_month
from apps.pa_draft_revenue_items
where 
    last_update_date >= to_date('2019-10-01', 'yyyy-mm-dd')
    and last_update_date < to_date('2019-12-01', 'yyyy-mm-dd')
group by project_id

答案 1 :(得分:0)

您必须将子查询的结果集与主查询的行链接起来,链接用project_id

表示

您更改的查询:

select 
    PROJECT_ID, 
    sum(AMOUNT), 
    ( 
        select sum(amount) 
        from APPS.pa_draft_revenue_items lastmonth
        where to_char(LAST_UPDATE_DATE,'MM')='10' 
        AND to_char(LAST_UPDATE_DATE,'YYYY')='2019'
        AND lastmonth.project_id = main.project_id
    ) AMOUNT_LAST_MONTH
from APPS.pa_draft_revenue_items main
where PROJECT_ID IN (
    select PROJECT_ID 
    from APPS.pa_draft_revenue_items
    where 
        to_char(LAST_UPDATE_DATE,'MM')='11' 
        AND to_char(LAST_UPDATE_DATE,'YYYY')='2019' 
) 
GROUP by PROJECT_ID, amount ;

答案 2 :(得分:0)

我会坚持要求您使用sysdate,因为它将变得通用,如下所示:

select 
    project_id, 
    sum(case when trunc(last_update_date,'month') = trunc(add_months(sysdate, -1),'month') then amount end) amount_last_month, 
    sum(case when trunc(last_update_date,'month') = trunc(sysdate,'month') then amount end) amount_this_month
from apps.pa_draft_revenue_items
where 
    last_update_date >= trunc(add_months(sysdate, -1),'month')
    and last_update_date < trunc(add_months(sysdate, 1),'month')
group by project_id

干杯!