我对此感到困惑:
SELECT request_id, SUM( cc_amount ) AS amt,
DATE_FORMAT( transaction_datetime, '%b %y' ) AS tdate
FROM ee_request_cc
GROUP BY DATE_FORMAT( transaction_datetime, '%b %y' )
UNION
SELECT request_id, SUM( request_amount ) AS amt,
DATE_FORMAT( transaction_date, '%b %y' ) AS tdate
FROM ee_request_paypal
GROUP BY DATE_FORMAT( transaction_date, '%b %y' )
我得到了:
id amt tdate
20 86.00 Mar 12
80 5.00 Apr 12
23 55.00 Mar 12
而我想在3月和4月添加所有金额,如:
id amt tdate
20 141.00 Mar 12
80 5.00 Apr 12
请建议我查询中的更改。
答案 0 :(得分:1)
试试这个:
select sum(amt), DATE_FORMAT(tdate, '%b %y') from (
SELECT amount1 AS amt, transaction_dt AS tdate
FROM table1
UNION ALL
SELECT request_amount, tr_date
FROM table2
) s
GROUP BY YEAR(tdate), MONTH(tdate)
请注意,您不应该从分组结果中获取ID ...您会选择哪一个?
同样按数字分组必须比将日期转换为字符串然后按字符串分组更快。
答案 1 :(得分:0)
你使用一个englobing SELECT和amt和GROUP BY tdate
SELECT id, SUM(amt) as samt, tdate
FROM (YOUR_ABOBE_QUERY) AS thequery
GROUP BY thequery.tdate
答案 2 :(得分:0)
您需要获取所有结果,然后执行聚合:
SELECT table_both.request_id, table_both.tdate, SUM(table_both.amount) AS amt
FROM (SELECT request_id, cc_amount AS amt, DATE_FORMAT(transaction_datetime,'%b %y') AS tdate
FROM table1
UNION ALL --Don't remove the duplicates
SELECT request_id, request_amount, DATE_FORMAT(transaction_date,'%b %y')
FROM table2) table_both
GROUP BY table_both.request_id, table_both.tdate --You don't need to add the format function in the group by