![](/img/trans.png)
[英]Oracle SQL - How to compare the number of rows between 2 sets in the same table?
[英]How to compare rows in same table for Oracle
目前我有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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.