2013-03-10 107 views
0

假設我有SELECT SUM()的條件在MySQL

SELECT `Type`, `Originating Country Code`,`Originating Currency Code`, SUM(`Principal Amount`) as Total 
FROM `colab` 
WHERE (`Destination Country Code`='PH' 
    AND `Destination Currency Code`='PHP' 
    AND `Type` = 'PAID') || (`Destination Country Code`='PH' 
    AND `Destination Currency Code`='USD' 
    AND `Type`= 'PAID') 
    GROUP BY `Type` 

是工作的罰款,並返回true,請參見下面的

country_code | Currency_Code | Type | Principal 

======================================================= 
| PH   | PHP   | PAID | 200 
======================================================= 

我的問題是我想單獨貨幣的本金總額與美元值。請參閱記錄我的數據庫裏面

country_code | Currency_Code | Type | Principal 

======================================================= 
| PH   | PHP   | PAID | 100 
| PH   | USD   | PAID | 100 
======================================================= 

回答

3

嘗試此查詢:

SELECT `Currency_Code`, SUM(`Principal Amount`) as Total 
FROM `table` 
GROUP BY `Currency_Code` 
+0

喜先生夢食者,任何想法我怎麼能做出另一個條件? – phphopzter 2013-03-10 03:24:32

+0

@phphopzter你可以更具描述性的條件?就像你想'type'字段是'W'或者你的'country_code'是'PH'或者類似的東西? – hjpotter92 2013-03-10 03:26:36

+0

嗨,謝謝,我只想插入另一個WHERE子句?但我認爲它不能在我的查詢權?這就是爲什麼即時查找mySQL查詢功能,以保持1個或更多的條件。謝謝 – phphopzter 2013-03-10 03:30:39

0

您需要使用GROUP BY

SELECT `Currency Code`, SUM(`Principal Amount`) as Total 
FROM `table` 
WHERE `Country Code`='PH' 
    AND `Type` LIKE '%W%' 
GROUP BY `Currency Code` 
1

你可以使用一個GROUP BY像這樣:

SELECT `Currency_Code`, SUM(`Principal Amount`) as Total 
FROM `table` 
WHERE `Country Code`='PH' 
    AND `Type` LIKE '%W%' 
GROUP BY `Currency_Code` 

如果你想添加更多的條件,只是用ANDOR添加更多的零部件到WHERE條款如:

SELECT `Currency_Code`, SUM(`Principal Amount`) as Total 
FROM `table` 
WHERE `Country Code`='PH' 
    AND `Type` LIKE '%W%' 
    AND `Currency_Code` IN('USD', 'CAD', 'YEN') 
    AND `Principal_Amount` > 10 
GROUP BY `Currency_Code` 
0

廣東話你只需要改變根據您的需要查詢? 我的意思是您的預期結果我推斷您需要基於Type或country_code的結果,因此從查詢中刪除「AND Currency Code ='PHP'」將會給您預期的結果。

0

將你的標準分解成一個子查詢並加入它。只要添加儘可能多的規則就可以了。

SELECT `Country Code`, `Currency Code`, `Type`, 
     SUM(`Principal Amount`) as Total 
FROM `table` 
JOIN (
    SELECT 'PH' as a, 'PHP' as b, '%W%' as c 
    UNION SELECT 'PH', 'USD', '%W%' 
    UNION SELECT 'PY', 'PYC', '%H%' 
) AS criteria 
    ON (`table`.`Country Code` = criteria.a and 
     `table`.`Currency Code` = criteria.b and 
     `table`.`Type` like criteria.c) 
GROUP BY `Country Code`, `Currency Code`, `Type`