全部加总和

时间:2018-08-08 12:20:38

标签: sql postgresql

我有2张桌子:

表1

mmsi   type   l   w   flag   value
123    456    A   B   C      37
236    567    X   Y   Z      28

表2

mmsi   type   l   w   flag   value
123    456    A   B   C      30
234    567    X   Y   Z      20

我想运行一个查询以获取唯一值,并为每行获取最后一个字段中存储的值的总和:

决赛桌

mmsi   type   l   w   flag   value
123    456    A   B   C      67
234    567    X   Y   Z      20
236    567    X   Y   Z      28

我该怎么办?我正在尝试UNION ALL和SUM

SELECT "mmsi", "type", "l", "w", "flag", "value", SUM ("value")
FROM (SELECT "mmsi", "type", "l", "w", "flag", "value" FROM "table 1" UNION ALL
SELECT "mmsi", "type", "l", "w", "flag", "value" FROM "table 2") as def
GROUP BY "mmsi", "type", "l", "w", "flag", "value"

但这给我以下错误结果:

mmsi   type   l   w   flag   value  sum
123    456    A   B   C      37     37
123    456    A   B   C      30     30
234    567    X   Y   Z      20     20
236    567    X   Y   Z      28     28

谢谢!

1 个答案:

答案 0 :(得分:3)

您需要从valueselect中删除group by

SELECT "mmsi", "type", "l", "w", "flag", SUM("value")
FROM (SELECT "mmsi", "type", "l", "w", "flag", "value" FROM "table 1" 
      UNION ALL
      SELECT "mmsi", "type", "l", "w", "flag", "value" FROM "table 2"
     ) as def
GROUP BY "mmsi", "type", "l", "w", "flag";