2016-06-19 98 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 

我不現在如何顯示付費價值。

任何幫助表示讚賞。

回答

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

嘗試使用和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; 

這個問題是相關的位:

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