简体   繁体   中英

MySQL combine results from UNION of same-scheme tables

There are two tables with the same structure: 'imsc_storage_users' & 'imsc_storage_users_archive'.

My current SELECT/UNION:

SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
FROM  `imsc_storage_users`
UNION DISTINCT
SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
FROM  `imsc_storage_users_archive`
ORDER BY `correct` DESC,`minutes` ASC

I'm getting these results:

+--------------+---------------------+-----------+---------+---------+------+---------+
| cli          | ts                  | questions | answers | correct | last | minutes |
+--------------+---------------------+-----------+---------+---------+------+---------+
| 111111111111 | 2011-12-22 11:13:57 |        30 |      29 |      14 |   30 | 1305.47 |
| 222222222222 | 2011-12-15 13:39:16 |        26 |      24 |      13 |   24 |   15.67 |
| 333333333333 | 2011-12-15 13:39:39 |        26 |      25 |      11 |   25 |   15.18 |
| 444444444444 | 2011-12-15 13:39:39 |        25 |      21 |      11 |   25 |  280.53 |
| 111111111111 | 2011-12-22 11:13:57 |        25 |      21 |      10 |   25 |  373.87 |
| 555555555555 | 2011-12-19 15:46:15 |        11 |      10 |       5 |   10 |     3.8 |
| 666666666666 | 2011-12-15 13:39:16 |        14 |      10 |       4 |   10 |  321.64 |
| 777777777777 | 2011-12-19 08:34:36 |        15 |      11 |       4 |   13 |  474.66 |

Notice that '111111111111' appears twice?

I want it to be combined, so in the results set I get one row of '111111111111' which combines/sums all fields; 'questions' =>> 55.... etc' .

What would be the correct SQL?
Performance are NOT of an issue here.

Thank you!

SELECT `cli`,max(`ts`) AS ts, sum(`questions`) as questions, sum(`answers`) as answers,sum(`correct`) as correct,sum(`last`) as last,sum(`minutes`) as minutes
FROM (
  SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
  FROM  `imsc_storage_users`
  UNION ALL
  SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
  FROM  `imsc_storage_users_archive`
) AS baseview
GROUP BY cli
ORDER BY `correct` DESC,`minutes` ASC

Try:

SELECT `cli`,
       `ts`,
       sum(`questions`), 
       sum(`answers`),
       sum(`correct`),
       sum(`last`),
       sum(`minutes`)
FROM (SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
      FROM  `imsc_storage_users`
      UNION ALL
      SELECT `cli`,`ts`,`questions`, `answers`,`correct`,`last`,`minutes` 
      FROM  `imsc_storage_users_archive`) V
group by `cli`, `ts`
ORDER BY 5 DESC, 7 ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM