我如何获得每一列的总和

时间:2019-04-06 12:22:17

标签: mysql sql

表格

api_channel

 channel_id| channel_company
-----------+-------------
    1      |     copmany1     
    2      |     copmany2  
    3      |     copmany3 
    4      |     copmany4
    5      |     copmany5  
-----------+-------------        

充值

 id|amount|  status| channel_id
---+------+--------+------------
 1 | 248  | success|    2
 2 | 240  | failed |    1
 3 | 495  | failed |    1
 4 | 150  | success|    2
 5 | 278  | failed |    3
---+------+--------+-------------  

想要的结果:

 id|channel_company|success_total| failed_total | pending_total
---+---------------+-------------+--------------+--------------
 1 |    copmany1   |    0        |    735       |       0
 2 |    copmany2   |   398       |     0        |       0
 3 |    copmany3   |    0        |    278       |       0
 4 |    copmany4   |    0        |     0        |       0
 5 |    copmany5   |    0        |     0        |       0
---+---------------+-------------+--------------+--------------  

我的查询

SELECT 
  SUM(R.recharge_amount) AS total, A.channel_id, A.channel_company, 
  R.api_channel, R.status, R.recharge_amount, R.created_at 
FROM api_channels A LEFT JOIN recharges R 
  ON R.api_channel = A.channel_id 
WHERE R.status ='Success' OR R.status ='Failed' OR R.status ='Pending' 
  AND CAST(R.created_at AS DATE)= CURRENT_DATE GROUP BY R.status

有三种状态,成功,失败,待处理,但是有时这些值变为空,例如充值表会看到没有待处理的充值。

2 个答案:

答案 0 :(得分:2)

加入2个表并应用条件聚合:

select
  a.channel_id,
  a.channel_company,
  sum(case when r.status = 'success' then r.amount else 0 end) success_total,
  sum(case when r.status = 'failed' then r.amount else 0 end) failed_total,
  sum(case when r.status = 'pending' then r.amount else 0 end) pending_total
from api_channel a left join recharges r
on a.channel_id = r.channel_id
group by 
  a.channel_id,
  a.channel_company

答案 1 :(得分:2)

一种方法是条件聚合,即使用CASE表达式作为sum()的参数,如果状态是您要计数的状态,则仅产生数量,否则使用0。对于没有coalesce()且处于通缉状态的公司,请使用0的默认值recharges

SELECT ac.channel_id id,
       ac.channel_company,
       coalesce(sum(CASE
                      WHEN r.status = 'success' THEN
                        r.amount
                      ELSE
                        0
                    END), 0) success_total,
       coalesce(sum(CASE
                      WHEN r.status = 'failed' THEN
                        r.amount
                      ELSE
                        0
                    END), 0) failed_total,
       coalesce(sum(CASE
                      WHEN r.status = 'pending' THEN
                        r.amount
                      ELSE
                        0
                    END), 0) pending_total
       FROM api_channel ac
            LEFT JOIN recharges r
                      ON r.channel_id = ac.channel_id
       GROUP BY ac.channel_id,
                ac.channel_company;