I-AM-OBODO Posted December 13, 2016 Share Posted December 13, 2016 Hello guys, I'm try to sum rows in a UNION but having a hard time about it $stmt = $pdo->prepare("SELECT due_date, SUM(amount_paid) FROM ( SELECT due_date, amount_paid FROM table1 union all SELECT due_date, amount_paid FROM table2 UNION ALL )x GROUP BY MONTH"); $stmt->execute(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['x']; thanks Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted December 13, 2016 Solution Share Posted December 13, 2016 For a start, too many "UNIONS". SELECT MONTH(due_date) as month , SUM(amount_paid) as total FROM ( SELECT due_date, amount_paid FROM table1 UNION ALL SELECT due_date, amount_paid FROM table2 )x GROUP BY month If you are having to do that, it looks like your table1 and table2 should be a single table with an additional identifier column. Quote Link to comment Share on other sites More sharing options...
benanamen Posted December 13, 2016 Share Posted December 13, 2016 I agree with @Barand on the single table. Whenever I see UNION being used on a forum the DB design is always not properly normalized. Quote Link to comment Share on other sites More sharing options...
I-AM-OBODO Posted December 13, 2016 Author Share Posted December 13, 2016 For a start, too many "UNIONS". SELECT MONTH(due_date) as month , SUM(amount_paid) as total FROM ( SELECT due_date, amount_paid FROM table1 UNION ALL SELECT due_date, amount_paid FROM table2 )x GROUP BY month If you are having to do that, it looks like your table1 and table2 should be a single table with an additional identifier column. I think i agree with you. I have changed the table to a singe table with an identifier. I created two tables cos of an issue but i have been able to sail pass that now. thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.