sql - 如何在查询中链接两条记录
问题描述
我想共同计算利润,其中两种交易类型(放置(1)和赢得(2)或取消(3))都在指定的时间段内,或者只有放置的交易。
这是表架构:
CREATE TABLE transactions (
transaction_id integer,
reference_id integer,
customer_id integer,
amount integer,
transaction_date date,
transaction_type integer
);
使用以下数据:
INSERT INTO transactions
VALUES
(1,1, 100, 8,'2019-01-04',1),
(2,1, 100, 12,'2019-01-05',2),
(3,2, 100, 20,'2019-01-05',1),
(4,2, 100, 20,'2019-01-06',3),
(5,3, 101, 11,'2019-01-05',1),
(6,3, 101, 32,'2019-01-05',2),
(7,4, 102, 7,'2019-01-04',1),
(8,4, 102, 14,'2019-01-06',2),
(9,5, 102, 8,'2019-01-02',1),
(10,5, 102, 8,'2019-01-04',3),
(11,6, 102, 20,'2019-01-06',1),
(12,7, 103, 25,'2019-01-06',1),
(13,8, 103, 10,'2019-01-06',1),
(14,9, 103, 5,'2019-01-01',1),
(15,10, 103, 40,'2019-01-06',1);
以及尝试的查询:
select customer_id, sum(won-placed+cancel) as profit
from
(select customer_id,
sum(case when transaction_type = 1 then amount else 0 END) AS placed,
sum(case when transaction_type = 2 then amount else 0 END) AS won,
sum(case when transaction_type = 3 then amount else 0 END) AS cancel
from transactions
where transaction_date > '2019-01-04'
group by 1) x
group by 1 order by 1
在这种情况下,例如对于客户 100,利润应该等于 0,因为应该只从给reference_id = 2
定transaction_id = 1
时间范围之前放置的位置开始计算。
transaction_type = 1
客户 200,利润应该是 -20,因为在给定的时间范围之后只有一个。
我不知道如何通过参考 ID 链接每笔交易,非常感谢任何帮助,谢谢!
解决方案
使用相关子查询
select customer_id, sum(won-placed+cancel) as profit
from
(select customer_id,
sum(case when transaction_type = 1 then amount else 0 END) AS placed,
sum(case when transaction_type = 2 then amount else 0 END) AS won,
sum(case when transaction_type = 3 then amount else 0 END) AS cancel
from transactions a
where transaction_date > '2019-01-04' and
exists (select 1 from transactions b where a.customer_id=b.customer_id
and b.transaction_date > '2019-01-04')
and not exists
(select 1 from transactions c where
a.customer_id=c.customer_id and transaction_date < '2019-01-05'
and a.reference_id=c.reference_id)
group by 1) x
group by 1 order by 1
输出:
customer_id profit
100 0
101 -21
102 -6
103 -75
推荐阅读
- .net - 使用 couchbase dotnet SDK 3.1 从 iis 联系 couchbase 服务器的问题
- reactjs - React Axios get call 不适用于授权标头
- sharepoint - 使用 Graph SDK 正确输入 site_ID
- image - 如何使用参数制作不和谐命令?
- javascript - 如何在 GET 请求完成将文本加载到 HTML 之前暂停执行?
- firebase - 使用 Blaze 计划在 Database Realtime 中限制 100 个同时连接
- android - 使用 Zip 运算符、Rxjava2 和 Retrofit 处理错误
- spring - Spring webflux security - 使用邮递员的基于表单的身份验证测试
- python - 在 Dialog 的 body 方法中创建 StringVar 时不保持其初始值
- python - 尝试使用枚举作为索引有效,但在 pycharm 中给出警告