【问题标题】:sumProduct in sqlsql中的sumProduct
【发布时间】:2015-09-11 11:14:35
【问题描述】:

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

【问题讨论】:

  • 样本数据和期望的结果会真正让您的表格更加清晰。
  • 从 select (c * e)/100*3423) 中删除最后一个括号

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


【解决方案1】:

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

select sum(c * e)
from #mytable1;

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

编辑:

你想要一个窗口函数:

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

【讨论】:

  • 请看示例数据,也许它有助于你了解我想要什么
  • 需要这样写:case when t.b like 'axr%' then (sum(t.c * t.e) /100*3234) end as sumProduct from #myTable t 看我的编辑。 @戈登谢谢你
【解决方案2】:

真诚地,我还没有理解您的代码。但是假设您有两个表,其中包含值和一个唯一的 Id(用于连接),那么也许我的实现可以帮助您获得灵感:

-- create new DB or point to an existing one
use [test];

CREATE TABLE [dbo].[table1](
    [id] [int] NOT NULL,
    [value] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[table2](
    [id] [int] NOT NULL,
    [value] [int] NOT NULL
) ON [PRIMARY]
GO

insert into table1 values (1, 5), (2, 10);
insert into table2 values (1, 2), (2, 4);

select sum(P.products) as sumproduct from
(select (t1.value * t2.value) as products from table1 as t1 inner join table2 as t2 on t1.id = t2.id) as P

【讨论】:

  • 我想对所有日期的所有格式为'axr%' 的两列的值进行求和。我正在使用 a,b,c..etc,因为这与他们所拥有的内容无关,我可能有一个 "ambigous column name error"。在我的代码中,您可以看到我有一个表,我正在尝试加入它自己,因为我写的第一件事是:select * into #myTable2 from #myTable1 。谢谢你的代码,它很有帮助
猜你喜欢
  • 2020-02-02
  • 2015-10-15
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多