PSQL:求和时的奇怪问题 - 乘以行数

时间:2015-12-08 23:28:50

标签: psql

这里是tv_1表:

id  | fig
-------------
111 | 500
222 | 200
111 | 300
111 | 200
111 | 300

此处tv_2

id  | test
-------------
111 | 50
111 | 70
111 | 40

当我执行此查询时:

SELECT sum(tv_1.fig), tv_2.id
FROM tv_1
JOIN tv_2 ON tv_1.id = tv_2.id
WHERE tv_1.id = 111
GROUP BY tv_2.id

我明白了:

sum  | id
-------------
3900 | 111

但我需要得到:

sum  | id
-------------
1300 | 111

我该怎么做?

1 个答案:

答案 0 :(得分:0)

找到了答案!

SELECT SUM(tv_1.fig), v.id
FROM tv_1
INNER JOIN (SELECT DISTINCT tv_2.id FROM tv_2) v ON v.id = tv_1.id
WHERE tv_1.id = 111
GROUP BY v.id

这给了我:

sum  | id
-------------
1300 | 111