【问题标题】:How to calculate SUM for each criteria in 1 field in SQL?如何计算 SQL 中 1 个字段中每个条件的 SUM?
【发布时间】:2020-09-28 22:16:07
【问题描述】:

我又回来了,哈哈,我正在尝试计算以下内容:

找出有多少用户在过去 30 天内至少有一次余额超过 2000 英镑,因此应该通过贷记借记来获取每个用户的余额。

我已附上数据库

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

SELECT user_id, (credit_amount - debit_amount) AS balance
FROM (SELECT A.user_id, A.type, B.type, A.amount AS debit_amount, B.amount AS credit_amount
      FROM public.transaction A, public.transaction B
      WHERE A.user_id = B.user_id
      AND a.type LIKE 'debit'
      AND b.type LIKE 'credit'
      AND A.created_at >= CURRENT_DATE - INTERVAL '30 days'
      AND A.created_at <= CURRENT_DATE) AS table_1
WHERE (credit_amount - debit_amount) > 2000
;

但是,user_id 3 由于在时间间隔内没有信用而被跳过,并且一些值被遗漏了。任何帮助都会很好,谢谢。

【问题讨论】:

    标签: sql postgresql date pivot window-functions


    【解决方案1】:
    SELECT user_id, 
       c.credit_amount - b.debit_amount AS balance
    FROM public.transaction a
    
    JOIN (SELECT 
        user_id, type, amount AS debit_amount, 
      FROM public.transaction 
      where a.type LIKE 'debit') b on a.user_id = b.user_id
    
    JOIN (SELECT
      user_id, type, amount AS credit_amount
      FROM public.transaction 
      where type LIKE 'credit') c on a.user_id = c.user_id
    
    WHERE a.created_at >= CURRENT_DATE - INTERVAL '30 days'
    AND a.created_at <= CURRENT_DATE) AS table_1
    AND (c.credit_amount - b.debit_amount) > 2000
    GROUP BY a.user_id;
    

    【讨论】:

      【解决方案2】:

      找出过去 30 天内有多少用户至少有一次的余额超过了 2000 英镑,

      您可以使用窗口函数计算每个用户在此期间的运行余额。然后,您只需要统计运行余额曾经超过阈值的不同用户:

      select count(distinct user_id)  no_users
      from (
          select 
              user_id,
              sum(case when type = 'credit' then amount else -amount end) 
                  over(partition by user_id order by created_at) balance
          from transaction
          where created_at >= current_date - interval '30' day and created_at < current_date
      ) t
      where balance > 2000
      

      【讨论】:

      • 它返回一个错误,说“在或 noear 的语法错误”)“”
      • @Stephen:刚刚修正了错字(case 语句中缺少end);
      【解决方案3】:

      使用条件聚合:

      select user_id,
             (sum(amount) filter (where type = 'credit') -
              coalesce(sum(amount) filter (where type = 'debit'), 0)
             )
      from public.transaction t
      where t.created_at >= CURRENT_DATE - INTERVAL '30 days' and
            t.created_at < CURRENT_DATE
      group by user_id;
      

      【讨论】:

      • @斯蒂芬。 . .我有,但这些天我大部分时间都在工作和待在家里。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      相关资源
      最近更新 更多