SQL - 在不同的表中对具有相同ID的多行进行求和

时间:2016-03-09 23:50:08

标签: sqlite

我有3张桌子:

A:
ID | col1 | col2 | have
1  |  x   |   x  |  2
2  |  x   |   y  |  3

B:
ID | col1 | have
1  |  x   |  1
1  |  x   |  5

C:
ID | have
3  | 8
2  | 5
1  | 2

ID不是主键,只是外键。

我无法编写一个将所有这些内容相加的查询。这是我的工作,我不确定它为什么不起作用:

SELECT ID, SUM(have)
    FROM (
        SELECT ID, SUM(have) AS have
            FROM A
            GROUP BY ID
        UNION
        SELECT ID, SUM(have) AS have
            FROM B
            GROUP BY ID
        SELECT ID, SUM(have) AS have
            FROM C
            GROUP BY ID
    )
    GROUP BY ID

我在python中使用sqlite3,但我怀疑它会有什么不同,因为这是非常基本的SQL查询 - 因此错误在于数据或我的查询(猜测后者)。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

SELECT ID, SUM(have)
FROM (
    SELECT ID, SUM(have) AS have
        FROM A
        GROUP BY ID
    UNION ALL
    SELECT ID, SUM(have) AS have
        FROM B
        GROUP BY ID
    UNION ALL
    SELECT ID, SUM(have) AS have
        FROM C
        GROUP BY ID
)
GROUP BY ID

尝试这一点,当你使用UNION时,它只使用UNION ALL整合了所有结果的唯一结果,你必须为你正在联合的所有SUM执行此操作。