我有2个查询
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')
他们返回结果,所以一切都好。但是,我需要获得包含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')