mysql总和一个表但不同的类型

时间:2012-12-26 08:38:50

标签: mysql sql select

task_payments

task_payments

SELECT t.id AS task_id, t.name, t.created_at
       ,COALESCE(SUM(tp1.amount),0) AS paid
       ,COALESCE(SUM(tp2.amount),0) AS paid_back
       FROM tasks AS t
       LEFT JOIN task_payments AS tp1 ON tp1.task_id=t.id AND tp1.type='1'
       LEFT JOIN task_payments AS tp2 ON tp2.task_id=t.id AND tp2.type='0'
       WHERE t.customer_id='4'
       GROUP BY tp1.task_id, tp2.task_id
       ORDER BY t.id ASC

嗨,task_payments上有两种类型(1或0)。 0型被偿还。第1类已付款。我希望单独总金额作为结果。所以我想要结果; TASK_ID = 5 支付= 450 paid_back = 10 我应该使用加入。如果有过滤请求,我将在where子句中使用paid和paid_colums。例如:和paid_back> 0

2 个答案:

答案 0 :(得分:2)

以下查询可能会对您有所帮助:D

SELECT  x.*
FROM
    (
        SELECT  a.task_id,
                SUM(CASE WHEN b.type = 1 THEN b.amount ELSE 0 END) paid,
                SUM(CASE WHEN b.type = 0 THEN b.amount ELSE 0 END) paidBack
        FROM    tasks a
                LEFT JOIN task_payments b
                    ON a.id = b.task_id
        -- WHERE a.customer_id = 4
        GROUP BY a.task_id
    ) x
-- WHERE    x.paid > 100   -- sample Request

答案 1 :(得分:1)

除了JW的回答,我想建议一件事,

如果您的要求是默认空值,那么请转到

nvl(sum(field),0) instead of COALESCE(SUM(tp1.amount),0)

如果您的数据库不支持nvl,请转到IFNULL

希望这也可以帮助你:)