sql - sql中的sumProduct

标签 sql sql-server sql-server-2008 sql-server-2012 window-functions

我正在尝试在服务器上的表中实现 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

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

编辑: 样本数据和预期结果

只提及重要的列

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: 我需要一些语法方面的帮助。我正在尝试重写这部分:

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

作为

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

语法不正确,但应该可以这样工作

编辑 3: 让它工作像这样:

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

在代码的最后

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

我如何为每个日期执行此操作(假设日期是“a”列或任何名称)。 我怎样才能在上面的代码中合并 over (partition by a)

想要类似的东西

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

最佳答案

求和积的语法在 SQL 中非常简单:

select sum(c * e)
from #mytable1;

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

编辑:

你想要一个窗口函数:

select t.*,
       sum(c*e) over (partition by a)
from #mytable1;

关于sql - sql中的sumProduct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32522130/

相关文章:

mysql - 创建表时的 SQL 日期格式

sql - Postgres - 在标记的表连接后面引用完全限定的表或列

MYSQL 内连接(SQL 代码中的 If 语句?)

c# - 连接到 SQL Server 数据库

sql-server - 选择(无锁定)

sql-server - 如何从 Ubuntu 调试 MSSQL 驱动程序问题

sql - 我想显示所有具有指定列名的表

sql-server-2008 - 如何使用 SQL Server Dev Edition 加速集成测试

sql - PostgreSQL 中不同隔离级别的性能后果是什么?

sql-server-2008 - SQL 程序集与大型 XML 列上复杂查询的应用程序代码