SELECT SUM as field

时间:2009-10-08 14:54:20

标签: sql oracle

假设我有这张表

表(a,b,c,d)。数据类型并不重要。

我想这样做

select a as a1,b as b1,c as c1,
       (select sum(d) from table where a=a1 and b=b1) as total
from table
group by a,b,c

...但我找不到办法(sqldeveloper一直抱怨“未找到来自子句”。)

有办法吗?有可能吗?

3 个答案:

答案 0 :(得分:8)

SELECT  a as a1,b as b1,c as c1,
        (
        SELECT  SUM(d)
        FROM    mytable mi
        WHERE   mi.a = mo.a
                AND mi.b= mo.b
        ) as total
FROM    mytable mo
GROUP BY
        a, b, c

重写它更加简单有效:

SELECT  a AS a1, B AS b1, c AS c1, SUM(SUM(d)) OVER (PARTITION BY a, b) AS total
FROM    mytable
GROUP BY
        a, b, c

请注意SUM(SUM(d))此处。

最里面的SUM是聚合函数。它计算SUM(d) a-b-c - 明智。

最外面的SUM是分析函数。它对预先计算的SUM(d)的{​​{1}}进行求和,并将值与每行一起返回。

答案 1 :(得分:2)

杜你的意思是这样的吗?

select a as a1,
       b as b1,
       c as c1,
       sum(sum(d)) OVER (PARTITION BY a, b) AS total
from table
group by a,b,c

答案 2 :(得分:1)

你可以用别名来做:

SELECT a AS a1, b AS b1, c AS c1,
       (SELECT SUM(d)
           FROM test_t t_in
          WHERE t_in.a = t.a
            AND t_in.b = t.b) AS total
  FROM test_t t
 GROUP BY a, b, c