Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT SUM as field

Tags:

sql

oracle

Suppose i have this table

table (a,b,c,d). Datatypes are not important.

I want to do this

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

...but I can't find a way (sqldeveloper keeps complaining with "from clause not found".)

Is there a way? Is it possible?

like image 357
Tom Avatar asked Oct 08 '09 14:10

Tom


3 Answers

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

It's much more simple and efficient to rewrite it as this:

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

Note the SUM(SUM(d)) here.

The innermost SUM is the aggregate function. It calculates the SUM(d) a-b-c-wise.

The outermost SUM is the analytic function. It sums the precalculated SUM(d)'s a-b-wise, and returns the value along with each row.

like image 74
Quassnoi Avatar answered Oct 16 '22 08:10

Quassnoi


Du you mean something like this?

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
like image 38
Maximilian Mayerl Avatar answered Oct 16 '22 09:10

Maximilian Mayerl


you can do it with aliases:

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
like image 41
Vincent Malgrat Avatar answered Oct 16 '22 07:10

Vincent Malgrat