mysql分组总和金额

时间:2017-11-03 13:59:55

标签: mysql mysql-workbench

我正在尝试在每个总和上创建一个组来创建每个新列。

SELECT 
    distinct settlement_id,

    SUM(amount) AS `Order`,
    SUM(amount) AS `Refund`,
    SUM(amount) AS `Servicefee`,
    SUM(amount) AS `other_Transaction`

FROM
    settlements
WHERE
    transaction_type = 'order'
        OR transaction_type = 'refund'
        OR transaction_type = 'ServiceFee'
        OR transaction_type = 'other-transaction'

GROUP BY settlement_id ASC ,  transaction_type ASC

因为结果不是我想要的 workbench screenshot

这是一种结果,如下面的截图,这就是我要找的 excel screenshot

1 个答案:

答案 0 :(得分:1)

您可以同时使用SUMIF来实现此目标。

SELECT settlement_id, 
    SUM(IF(transaction_type = 'order',amount,0)) AS 'Order',
    SUM(IF(transaction_type = 'refund',amount,0)) AS 'Refund',
    SUM(IF(transaction_type = 'ServiceFee',amount,0)) AS 'Servicefee',
    SUM(IF(transaction_type = 'other-transaction',amount,0)) AS 'other_Transaction'
FROM settlements
GROUP BY settlement_id