我有兩個疑問連接在一個表中的兩個查詢在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')
但我通過幾個月有來自美國的付款,而不是資金的總和。
我該如何解決?
謝謝!
使用表別名並嘗試。 –