我有两个表table1和table2
表1:
id金额
1 394
2 897
2 345
3 123
表2:
id金额
2 876
3 890
3 876
4 908
我需要生成table3。加入两个表和SUM id明智并显示前30个金额持有人
表3:
id金额
2 2118
3 1889年
4 908
1 394
答案 0 :(得分:3)
您可以通过以下方式获取数据:
select table3.id, SUM (table3.amount) AS amount
FROM
(SELECT * FROM table1 UNION ALL SELECT * FROM table2) table3
GROUP BY table3.id
如果要创建包含上述数据的表格,可以这样做:
CREATE TABLE new_table select table3.id, SUM (table3.amount) AS amount
FROM
(SELECT * FROM table1 UNION ALL SELECT * FROM table2) table3
GROUP BY table3.id ;
答案 1 :(得分:0)
尝试使用此查询
SELECT a.id, SUM(a.amount)
FROM (
SELECT * FROM table1
UNION
SELECT * FROM table2) AS a
GROUP BY a.id
ORDER BY SUM(a.amount)
LIMIT 30 DESC;
以上查询将生成结果,现在用于创建新表使用
CREATE TABLE table3(
SELECT a.id, SUM(a.amount)
FROM (
SELECT * FROM table1
UNION
SELECT * FROM table2) AS a
GROUP BY a.id
ORDER BY SUM(a.amount)
LIMIT 30 DESC);
希望这会有所帮助......