2016-06-19 7 views
1

誰でも、計算に基づいて複数のフィールドを表示するmysqlクエリを助けることができます。複数のフィールド値の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 

Iドン支払われた価値をどのように表示するか。

何か助けていただければ幸いです。

答えて

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 

OR

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

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; 

SUM内部の場合は、この質問使用して試してみて、少し関連している:

MySql: is it possibile to 'SUM IF' or to 'COUNT IF'?

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 
関連する問題