任何人都可以帮助mysql查询根据计算显示多个字段。
我有以下数据:
ID | Supplier | Total | Tax | Shipping | Paid
1 | 2 | 100 | 10 | 5 | 0
2 | 2 | 50 | 5 | 2.5 | 1
现在我想要一个如下结果:
Supplier | Total Paid | Total Unpaid
2 | 57.5 | 115
我的查询如下(到目前为止)
SELECT suppliers.company, SUM(tax+shipping+total) as unpaid FROM poreceived LEFT JOIN suppliers ON suppliers.id = poreceived.supplierid WHERE paid = '0' GROUP BY supplierid
我现在不知道如何显示付费价值。
感谢任何帮助。
答案 0 :(得分:2)
尝试在SUM中使用和IF
SELECT
t.supplier,
SUM(IF(t.paid = 1, t.tax + t.shipping + t.total, 0)) AS total_paid,
SUM(IF(t.paid = 0, t.tax + t.shipping + t.total, 0)) AS total_unpaid
FROM poreceived AS t
GROUP BY t.supplier;
这个问题有点相关:
答案 1 :(得分:1)
SELECT
supplierid,
SUM(if(paid=1, total + tax + shipping, 0)) AS Paid,
SUM(if(paid=0, total + tax + shipping, 0)) AS Unpaid
FROM poreceived
GROUP BY supplierid
或强>
SELECT
supplierid,
total_paid + shipping_paid + tax_paid as Paid,
amount - total_paid - shipping_paid - tax_paid as Unpaid
FROM (
SELECT
supplierid
total + tax + shipping AS amount,
SUM(if(paid=1,total,0)) AS total_paid,
SUM(if(paid=1,shipping,0)) AS shipping_paid,
SUM(if(paid=1,tax,0)) AS tax_paid
FROM poreceived
GROUP BY supplierid
) t
答案 2 :(得分:1)
您可以使用数据透视查询来获取所需的输出:
SELECT Supplier,
SUM(CASE WHEN Paid = 1 THEN Total + Tax + Shipping ELSE 0 END) AS `Total Paid`,
SUM(CASE WHEN Paid = 0 THEN Total + Tax + Shipping ELSE 0 END) AS `Total Unpaid`,
FROM poreceived
GROUP BY Supplier