sql - plsql减去同一张表中的列
问题描述
我有一个简单的学生表。
name | amount | vdate
Josh | 15 | 01.01.2020
Steve | 25 | 05.04.2008
Josh | 40 | 01.01.2022
我想要做的是彼此减去 Josh 值。
我写了这个查询,但它不起作用
select name , sum(b.amount-a.amount) diff from
select name,amount from student a where name = 'Josh' and vdate='01.01.2020'
union all
select name,amount from student b where name = 'Josh' and vdate = '01.01.2022')
group by name
预期结果是:
name | diff
Josh | 25
Steve| 25
解决方案
你可以试试这段代码,
select
fname,
abs(sum(amount2)) amount
from
(
WITH
student(fname,amount,vdate) AS (
SELECT 'Josh' ,15, to_date('01102017','ddmmyyyy') from dual
UNION ALL SELECT 'Steve',25, to_date('01102017','ddmmyyyy') from dual
UNION ALL SELECT 'Josh' ,40 ,to_date('01102019','ddmmyyyy')from dual
)
select
h.fname,
h.amount,
decode((ROW_NUMBER() OVER(PARTITION BY fname order by vdate desc)),1,amount,amount* -1) amount2
from student h
)
group by
fname
;
我假设您获得的人的金额更大并减去其他值,您可以通过修改分区窗口中的 order by 子句来选择更大的日期,即
decode((ROW_NUMBER() OVER(PARTITION BY fname order by vdate desc)),1,amount,amount * -1) amount2
推荐阅读
- postgresql - Postgres ltree has-a-child 查询
- css - 将 svg 转换为 css 形状
- c# - 在 WPF c# 中为子窗口禁用捕获屏幕
- linux - 如何使用 awk 或 grep 在 Linux 上删除所有不匹配的数据
- java - 发送到 JAR 文件的环境变量可在 System.getProperty 中访问,但在 System.getenv 中
- kubernetes - 如何使用 kubectl 补丁将 Serviceaccout 添加到现有的 Clusterrolebinding
- c# - Regex.Replace 函数和读取文本文件
- django - Django Channels、Docker Compose、Errno 111] 连接调用失败('127.0.0.2',6379)
- c++ - 无法使用采用 std::array 的构造函数推断类中的类型
- magento2 - Magento 2 - 结账时自动预选客户账单地址 - 未设置默认值时