# Sum row in UNION

Go to solution Solved by Barand,

## Recommended Posts

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

##### Share on other sites

• Solution

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.

##### Share on other sites

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.

##### Share on other sites

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

##### Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.