gpt4 book ai didi

mysql求和一张表但类型不同

转载 作者:行者123 更新时间:2023-11-29 02:01:22 25 4
gpt4 key购买 nike

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

最佳答案

也许以下查询可以帮助您 :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

关于mysql求和一张表但类型不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14038007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com