Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sumProduct in sql

I'm trying implementing sumproduct (from excel) in my table on the server.

select * 
into #myTable2
from #myTable1

select
a, 
b,
c,
d,
e,
(
select (c * e)/100*3423) from #myTable1 t1
inner join #myTable t2
on t1.b = t2.b
where b like 'axr%'
) as sumProduct
from #myTable1

but this doesn't quite work. Can't spot the error, maybe i'm just tired or missing it.

edit: sample data and desired results

will mention only the important columns

c     e    b        a                             sumProduct      
2     4   axr1     2012.03.01                     2*4 + 3*8 
3     8   axr3     2012.03.01                     2*4 + 3*8 
7     5   axr23    2011.01.01                     7*5 + 3*2
3     2   axr34    2011.01.01                     7*5 + 3*2

EDIT2: I need some help with the syntax. I'm trying to rewrite this part:

select (c * e)/100*3423) from #myTable1 t1
    inner join #myTable t2
    on t1.b = t2.b
    where b like 'axr%'
    ) as sumProduct
    from #myTable1

as

case
when t.b like 'axr%' then
(sum(t.c * t.e) /100*3234) end as sumProduct from #myTable t

Can't get the syntax right, but should work like that

edit 3: got it to work like this:

case
when b like 'axr%' then
(sum(c*e)/100*3423)end as sumProduct

and at the end of the code

group by  --had an error without this
a,b,c,d,e 

How could i do this for every date (let's say the date is the column 'a' or whatever name). How can I incorporate over (partition by a) in the code above?

want something like

case 
when b like 'axr%' then
(sum(c*e)/100*3423 over (partition by a))end as sumProduct
like image 651
V2k Avatar asked Mar 01 '26 01:03

V2k


1 Answers

The syntax for a sum-product is very simple in SQL:

select sum(c * e)
from #mytable1;

I am not quite sure how this applies to your query, which seems to have other logic in it.

EDIT:

You want a window function:

select t.*,
       sum(c*e) over (partition by a)
from #mytable1;
like image 96
Gordon Linoff Avatar answered Mar 03 '26 15:03

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!