sql - PostgreSQL - 分组过滤特定行

标签 sql postgresql group-by

我在 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/

相关文章:

sql - 内置函数将每个单词的首字母大写

sql - 无法使用 vb6 将记录插入 ms access 2007

sql - PostgreSQL:变量字段中的 'Collating' 值变为单个结果

mysql - mysql 中按值等于 0 或不存在的行的行进行分组?

MySQL - 从行中创建列

sql - 使用 Microsoft Access SQL 将多个列中的数据合并到单个列中

MySQL:带有描述顺序问题的多个分组依据

带条件的 MySQL SUM DISTINCT

postgresql - 内部联接与执行 where in 子句

ruby-on-rails - ActiveRecord 或 Postgresql 创建新记录时设置错误的 ID