1

我有两个表table1和table2
table1:
id amount
1 394
2 897
2 345
3 123

table2:
id amount
2 876
3 890
3 876
4 908

我需要生成table3。明智地加入两个表和 SUM id 并显示前 30 名持有者。
表 3:
id 金额
2 2118
3 1889
4 908
1 394

4

2 回答 2

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 ;
于 2012-10-07T09:52:00.483 回答
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);

希望这可以帮助...

于 2012-10-07T09:56:06.713 回答