如何计算sql中1个字段中每个条件的总和?

zynd9foi  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(558)

我又回来了哈哈,我正在努力计算以下内容:
找出有多少用户在上面有余额£2000在最近30天内至少有一次,所以应该是贷记借记来获得每个用户的余额。
我已经附上了数据库

我尝试了以下方法,基本上是自连接,但是输出缺少值。

  1. SELECT user_id, (credit_amount - debit_amount) AS balance
  2. FROM (SELECT A.user_id, A.type, B.type, A.amount AS debit_amount, B.amount AS credit_amount
  3. FROM public.transaction A, public.transaction B
  4. WHERE A.user_id = B.user_id
  5. AND a.type LIKE 'debit'
  6. AND b.type LIKE 'credit'
  7. AND A.created_at >= CURRENT_DATE - INTERVAL '30 days'
  8. AND A.created_at <= CURRENT_DATE) AS table_1
  9. WHERE (credit_amount - debit_amount) > 2000
  10. ;

但是,由于在时间间隔内没有信用卡,用户\u id 3将被跳过&某些值将丢失。。任何帮助都很好,谢谢。

lztngnrs

lztngnrs1#

找出有多少用户在上面有余额£在过去的30天里至少有一次,
您可以使用窗口函数来计算每个用户在此期间的运行余额。然后,您只需统计运行平衡曾经超过阈值的不同用户:

  1. select count(distinct user_id) no_users
  2. from (
  3. select
  4. user_id,
  5. sum(case when type = 'credit' then amount else -amount end)
  6. over(partition by user_id order by created_at) balance
  7. from transaction
  8. where created_at >= current_date - interval '30' day and created_at < current_date
  9. ) t
  10. where balance > 2000
chhkpiq4

chhkpiq42#

使用条件聚合:

  1. select user_id,
  2. (sum(amount) filter (where type = 'credit') -
  3. coalesce(sum(amount) filter (where type = 'debit'), 0)
  4. )
  5. from public.transaction t
  6. where t.created_at >= CURRENT_DATE - INTERVAL '30 days' and
  7. t.created_at < CURRENT_DATE
  8. group by user_id;
e5nszbig

e5nszbig3#

  1. SELECT user_id,
  2. c.credit_amount - b.debit_amount AS balance
  3. FROM public.transaction a
  4. JOIN (SELECT
  5. user_id, type, amount AS debit_amount,
  6. FROM public.transaction
  7. where a.type LIKE 'debit') b on a.user_id = b.user_id
  8. JOIN (SELECT
  9. user_id, type, amount AS credit_amount
  10. FROM public.transaction
  11. where type LIKE 'credit') c on a.user_id = c.user_id
  12. WHERE a.created_at >= CURRENT_DATE - INTERVAL '30 days'
  13. AND a.created_at <= CURRENT_DATE) AS table_1
  14. AND (c.credit_amount - b.debit_amount) > 2000
  15. GROUP BY a.user_id;

相关问题