gpt4 book ai didi

sql - PostgreSQL - 分组过滤特定行

转载 作者:行者123 更新时间:2023-11-29 13:19:49 25 4
gpt4 key购买 nike

我在 Postgres 9.5 数据库中有 3 个表,如下所示,

阈值

id    threshold_amount
----------------------
111 100
112 200
113 80

customers - 每个客户都有一个 threshold_idthreshold

id   customer_name threshold_id
--------------------------------
313 abc 111
314 xyz 112
315 pqr 113

charges - 每个客户都有费用,所以这个表有 customer_id

id    customer_id  amount  post_date     
------------------------------------
211 313 50 4/1/2017
212 313 50 4/30/2017
213 313 50 5/15/2017
214 314 100 3/1/2017
215 314 50 3/21/2017
216 314 50 4/21/2017
217 314 100 5/1/2017
218 315 80 5/5/2017

我想查询它并按 charges.id 列的升序返回特定的 post_date with sum( amount ) == threshold_amount ,

结果集如下所示,

customer_id   post_date
-----------------------
313 4/30/2017
314 4/21/2017
315 5/5/2017

我已经尝试使用 sum( amount )group by customer_id 并调用将存储过程与 select 子句分开并传递 amountpost_datethreshold_amount 然后创建一个临时表,如果上述条件匹配,则将 post_date 插入其中,然后再次访问该临时表,但是它似乎无效所以我想知道是否有其他解决方案或者我可以在查询中执行此操作吗?

谢谢

最佳答案

您的问题是询问阈值的精确匹配。这基本上是一个累加和:

select cct.*
from (select ch.customer_id, ch.amount,
sum(ch.amount) over (partition by ch.customer_id order by post_date) as running_amount,
t.threshold_amount
from charges ch join
customers c
on ch.customer_id = c.id join
threshholds t
on c.threshold_id = t.id
) cct
where running_amount = threshold_amount;

关于sql - PostgreSQL - 分组过滤特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44022715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com