sql - 减法后如何添加新列
问题描述
我有一个观点。当我用 pc_no = 123 执行它时,得到这些结果
name |school |amount
Jone |Cambridge|400
Steve|London |400
Mark |Koln |200
paul |Barcelona|700
Harry|Paris |0
当我用其他 pc_no = 456 执行它时,得到这些结果
name |school |amount
Jone |Cambridge|300
Steve |London |400
Mark |Koln |500
Harry |Paris |50
我想要做的是看到这样的差异行和数量差异
name |school |lastAmount |FirstAmount |Diff
Jone |Cambridge |400 |300 |100
Mark |Koln |200 |500 |-300
paul |Barcelona |700 |0 |700
Harry|Paris |0 |50 |-50
我执行了这个查询来获取不同的行
select a.name, a.school,a.amount lastAmount, nvl(b.amount,0) FisrstAmount,
a.amount - b.amount Diff
from
(
select name,school,amount from SchemaName.ViewName where pc_no= 123
minus
select name,school,amount from SchemaName.ViewName where pc_no= 456
) a , SchemaName.ViewName b where
b.invoice_no =456
and a.name=b.name
and a.school=b.school
结果:
name |school |lastAmount |FirstAmount |Diff
Jone |Cambridge |400 |300 |100
Mark |Koln |200 |500 |-300
Harry|Paris |0 |50 |-50
我没有得到只有保罗的记录。
解决方案
您需要amount
这两组的值,所以minus
这不是您真正想要的。这仅显示第一个表中的值。
您可以通过将表完全外部连接在一起来获得此信息,不包括差异为零的那些行:
create table t1 (
nm varchar2(30),
school varchar2(30),
amount int
);
create table t2 (
nm varchar2(30),
school varchar2(30),
amount int
);
insert into t1 values ( 'Jone ', 'Cambridge', 300 );
insert into t1 values ( 'Steve', 'London', 400 );
insert into t1 values ( 'Mark', 'Koln', 500 );
insert into t1 values ( 'Harry', 'Paris', 50 );
insert into t2 values ('Jone ', 'Cambridge', 400 );
insert into t2 values ('Steve', 'London', 400 );
insert into t2 values ('Mark', 'Koln', 200 );
insert into t2 values ('paul', 'Barcelona', 700 );
insert into t2 values ('Harry', 'Paris', 0 );
select nm, school,
nvl ( t1.amount, 0 ) first_amount,
nvl ( t2.amount, 0 ) last_amount,
nvl ( t2.amount, 0 ) - nvl ( t1.amount, 0 ) diff
from (
select 1 tab, t1.* from t1
) t1 full outer join (
select 2 tab, t2.* from t2
) t2
using ( nm, school )
where nvl ( t1.amount, 0 ) - nvl ( t2.amount, 0 ) <> 0;
NM SCHOOL FIRST_AMOUNT LAST_AMOUNT DIFF
Jone Cambridge 300 400 100
Mark Koln 500 200 -300
paul Barcelona 0 700 700
Harry Paris 50 0 -50
推荐阅读
- elasticsearch - 在 ElasticSearch 7.6 中使用空格搜索关键字
- python - Python:编写斐波那契协程
- c++ - 通过基引用进行分配的对象切片是否定义明确?
- php - 如何在 php lik .env 文件中设置环境变量
- javascript - 如何将新值推送到 React 中的对象数组中
- c# - 如何使用 Unity 在 ARfoundation 中使用图像跟踪显示不同的预制件?
- javascript - 转换后自定义元素在 IE 11 中不起作用
- php - 如何获取用户发送的最后一条消息。我的代码给了我错误“explode() 期望参数 2 是字符串,给定对象”
- tensorflow - 初始化 CUDnn 失败
- angular - 多个用户未使用 RtcPeerConnection 在 WebRtc 中连接