2

任务付款

任务付款

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=5paid=450paid_back=10 我应该使用join。如果有过滤请求,我将在 where 子句中使用paid 和paid_colums。例如:和paid_back>0

4

2 回答 2

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
于 2012-12-26T08:41:15.680 回答
1

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

如果您的要求是默认空值,请选择

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

如果你的数据库不支持nvl然后去IFNULL

希望这也对你有帮助:)

于 2012-12-26T08:57:14.157 回答