SQL中的sumProduct

V2k*_*V2k 0 sql sql-server sql-server-2008 window-functions sql-server-2012

我正在尝试在服务器上的表中实现sumproduct(来自excel)。

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
Run Code Online (Sandbox Code Playgroud)

但这并不完全有效。无法发现错误,也许我只是累了或想念它。

编辑: 样本数据和所需结果

只提及重要的专栏

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
Run Code Online (Sandbox Code Playgroud)

EDIT2:我需要一些语法帮助。我正在尝试重写这一部分:

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
Run Code Online (Sandbox Code Playgroud)

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

无法正确使用语法,但应该可以正常工作

编辑3: 让它像这样工作

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

在代码的末尾

group by  --had an error without this
a,b,c,d,e 
Run Code Online (Sandbox Code Playgroud)

我该如何针对每个日期执行此操作(假设日期是“ a”列或其他名称)。如何将其合并 over (partition by a)到上面的代码中?

想要像

case 
when b like 'axr%' then
(sum(c*e)/100*3423 over (partition by a))end as sumProduct
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 6

sum-product的语法在SQL中非常简单:

select sum(c * e)
from #mytable1;
Run Code Online (Sandbox Code Playgroud)

我不太确定这如何应用于您的查询,其中似乎包含其他逻辑。

编辑:

您需要一个窗口函数:

select t.*,
       sum(c*e) over (partition by a)
from #mytable1;
Run Code Online (Sandbox Code Playgroud)