Sql 如何为Oracle比较同一表中的行

Sql 如何为Oracle比较同一表中的行,sql,oracle11g,Sql,Oracle11g,目前我有PLSQL代码来处理和计算数据。但问题是,在没有PLSQL的情况下,也就是说,使用Oracle分析函数的情况下,可以做到这一点吗 表包含计划和实际的数据快照,如下所示: data_snap_id actual_dt planned_dt amount ------------ --------- --------- ------ 1 2014-10-01 20.00 1

目前我有PLSQL代码来处理和计算数据。但问题是,在没有PLSQL的情况下,也就是说,使用Oracle分析函数的情况下,可以做到这一点吗

表包含计划和实际的数据快照,如下所示:

data_snap_id    actual_dt   planned_dt  amount
------------    ---------   ---------   ------
1                           2014-10-01  20.00
1                           2014-10-02  10.00
1                           2014-10-03  5.00
1                           2014-10-04  10.00
1                           2014-10-05  51.00
1                           2014-10-06  10.00
1                           2014-10-07  50.00
1                           2014-10-08  15.00
1                           2014-10-09  55.00
1                           2014-10-10  100.00
2               2014-10-01  2014-10-01  25.00
2               2014-10-02  2014-10-02  5.00
2               2014-10-03  2014-10-03  15.00
2               2014-10-04  2014-10-04  15.00
2               2014-10-05  2014-10-05  5.00
2                           2014-10-06  10.00
2                           2014-10-07  50.00
2                           2014-10-08  15.00
2                           2014-10-09  55.00
2                           2014-10-10  10.00
预期的查询输出如下所示:

action_date planned_amount  actual_amount   adds    deletes
----------- --------------  -------------   ----    -------
2014-10-01  20.00           25.00           5.00    0.00
2014-10-02  10.00           5.00            0.00    5.00
2014-10-03  5.00            15.00           10.00   0.00
2014-10-04  10.00           15.00           5.00    0.00
2014-10-05  51.00           5.00            0.00    46.00
2014-10-06  5.00                            0.00    0.00
2014-10-07  50.00                           0.00    0.00
2014-10-08  15.00                           0.00    0.00
2014-10-09  55.00                           0.00    0.00
2014-10-10  100.00                          0.00    90.00

假设我正确理解了您的问题,您可以使用带有max和case的聚合查询来分离计划金额和实际金额,然后使用子查询来获得添加和删除:

select action_date, 
  planned_amount,
  actual_amount,
  case when actual_amount-planned_amount < 0 
       then 0 else actual_amount-planned_amount end adds,
  case when planned_amount-actual_amount < 0 
       then 0 else planned_amount-actual_amount end deletes
from (
  select planned_dt action_date,
       coalesce(max(case when actual_dt is null then amount end),0) planned_amount,
       coalesce(max(case when actual_dt is not null then amount end),0) actual_amount
  from yourtable
  group by planned_dt
  ) t
order by action_date