求和每个行的参考不同的coloumn?

时间:2017-11-06 15:53:53

标签: sql postgresql

是否可以执行求和查询,其中总和的每一部分的行是从连接中确定的?

例如,如果我有表

table A
id | value
1  |  10
2  |  15
3  |  10

table b
id  | b  | c
1  | 2  | 3
2  | 1  | 2

是否可以执行SUM(tableA.value * tableB.<specific_column>)其中,SUM直接作为连接执行,或者从规范中获取连接表,为了参数,字符串&#34; bcb&#34; ?

编辑:

我希望实现的最终结果与此相同:

SUM(SELECT value * b FROM tableA a JOIN tableB b ON b.id = 1 WHERE a.id = 1,
    SELECT value * c FROM tableA a JOIN tableB b ON b.id = 1 WHERE a.id = 2,
    SELECT value * b FROM tableA a JOIN tableB b ON b.id = 2 WHERE a.id = 3);

我想其中有两个部分:A的简单连接和B中的选定值,使B缩小为单个selectValue列。

感谢。

2 个答案:

答案 0 :(得分:1)

正如评论中所说,向我们展示你真正想要的输出应该更好,但据我所知,你想做的事情如下:

SELECT id, SUM(a.value * b.b)
  FROM a JOIN b USING(id)
 GROUP BY id;

这是你想要的?我真的不了解你&#34; bcb&#34;点......

不是因为在你的评论中你说的是SUM(值,值,值),我认为你想要添加这些值,我会做这样的事情:

WITH 
sum1 AS (SELECT value * b AS res 
           FROM tableA a 
           JOIN tableB b ON b.id = 1
          WHERE a.id = 1),
sum2 AS (SELECT value * c AS res 
           FROM tableA a 
           JOIN tableB b ON b.id = 1 
          WHERE a.id = 2),
sum3 AS (SELECT value * b AS res 
           FROM tableA a 
           JOIN tableB b ON b.id = 2 
          WHERE a.id = 3)
SELECT SUM(sum1.res + sum2.res + sum3.res)
  FROM sum1, sum2, sum3;

答案 1 :(得分:0)

我测试了@HervéPiedvache的代码,它返回NULL,因为SELECT value * b AS val FROM tableA a JOIN tableB b ON b.id = 1 WHERE a.id = 1有两行。解决方法是:

SELECT SUM(val) FROM
    (SELECT value * b AS val FROM tableA a JOIN tableB b ON b.id = 1 WHERE a.id = 1
    UNION
    SELECT value * c AS val FROM tableA a JOIN tableB b ON b.id = 1 WHERE a.id = 2
    UNION
    SELECT value * b AS val FROM tableA a JOIN tableB b ON b.id = 2 WHERE a.id = 3) data;