2014-04-21 183 views
0

我有兩個疑問連接在一個表中的兩個查詢在SQL

SELECT date_format(payments.paymentdate, '%m'), 
     SUM(payments.amount) 
FROM payments 
WHERE payments.`customerNumber` IN 
(
    SELECT customers.`customerNumber` 
    FROM customers 
    WHERE customers.`country` = 'USA' 
    and customers.`customerNumber` = payments.`customerNumber` 
) 
GROUP BY date_format(payments.paymentdate, '%m') 

SELECT date_format(payments.paymentdate, '%m') , 
     SUM(payments.amount) 
FROM payments 
GROUP BY date_format(payments.paymentdate, '%m') 

他們返回結果,因此一切都OK。但是,我需要得到3列結果 - date_format(payments.paymentdate, '%m'),SUM(payments.amount) (where country is USA)SUM(payments.amount)(與所有國家)。

我試過下面的查詢

SELECT date_format(payments.paymentdate, '%m') , 
     SUM(payments.amount), 
     (
      SELECT SUM(payments.amount) 
      FROM payments 
      WHERE payments.`customerNumber` IN 
      (
      SELECT customers.`customerNumber` 
      FROM customers WHERE customers.`country` = 'USA' 
      and customers.`customerNumber` = payments.`customerNumber` 
     ) 
     ) 
FROM payments 
GROUP BY date_format(payments.paymentdate, '%m') 

但我通過幾個月有來自美國的付款,而不是資金的總和。

我該如何解決?

謝謝!

+0

使用表別名並嘗試。 –

回答

0

您希望所有付款的總和和一些付款的總和。

這是「if」語句的完美選擇。我仍然想你早晚要'%Y-%m',不要混淆2014年4月和2015年4月。

SELECT date_format(payments.paymentdate, '%m') as month, SUM(payments.amount) as amount_total, sum(if(customers.country='USA', payments.amount, 0)) as amount_USA 
FROM payments 
inner join customers on customers.customerNumber = payments.customerNumber 
GROUP BY date_format(payments.paymentdate, '%m') 
+0

這有效!非常感謝! – user3556682

+0

@ user3556682:如果它很好,那麼您可以將答案標記爲正確,如果它對您有幫助,您可以加註。這就是我們獲得信譽得分的地方。 ;-) – flaschenpost