Why is GROUP BY clause missing rows Can't understand a strange behavior of GROUP BY clause:
SELECT id, SUM(num) as sum
FROM (
    SELECT 1 AS id, 2 AS num UNION
    SELECT 1, 3) AS a
GROUP BY id

results in:
id  | sum |
----|-----|
1   | 5   |

but
SELECT id, SUM(num) as sum
FROM (
    SELECT 1 AS id, 2 AS num UNION
    SELECT 1, 2 /*!*/) AS a
GROUP BY id

results in:
id  | sum |
----|-----|
1   | 2   |
UNION excludes duplicate rows.
You want to use UNION ALL in this example:
 SELECT id, SUM(num) as sum
 FROM (
     SELECT 1 AS id, 2 AS num UNION ALL
     SELECT 1, 2 /*!*/) AS a
 GROUP BY id

Results:
id          sum
----------- -----------
1           4