【问题标题】:Update Sum GroupBy更新总和 GroupBy
【发布时间】:2016-10-08 11:40:44
【问题描述】:

桌数:1

Col1  Col2  Col3  Total
+10     0   Prod1 
0     -10   Prod1
0     -20   Prod2
+20    0    Prod2

我想要-

Col1  Col2  Col3  Total
+10     0   Prod1  0
0     -10   Prod1  0
0     -20   Prod2  0
+20    0    Prod2  0

我想在 Total col 中为 Col3 中的相同产品求和 col1 和 col2。 我如何做到这一点?

DoCmd.RunSQL "UPDATE Table1 SET Table1.Total = (Select Sum(Table1.Total) from Table1 Group By Table1.Col3)"

请注意,我在这里不是简单地添加 2 列。它相当于我的目标 Excel 的 SumIf。

【问题讨论】:

  • 这里为什么需要SUM
  • 我的目标是从 Total col 中去除零。为了实现这一点,我需要对 group by 求和,然后在总 col 中更新它。谢谢。
  • 我猜,我们都可以提供几乎相同的解决方案:D

标签: sql ms-access group-by sum vba


【解决方案1】:

您的查询可能如下所示:

Select coalesce(Sum(Table1.Col1),0) + Coalesce(Sum(Table1.Col2),0)
   from Table1 
   Group By Table1.Col3  

使用coalesce,我们确保sum 之一不会null

update 部分:

UPDATE Table1 t1 SET t1.Total = (
    Select coalesce(Sum(t2.Col1),0) + Coalesce(Sum(t2.Col2),0)
       from Table1 t2 
       where t2.Col3=t1.Col3
       Group By t2.Col3 
    )

【讨论】:

  • 为什么?这应该有效。也许有一些 vba 限制?
  • 当然这只是查询的select 部分。你应该自己添加update部分
  • 感谢 Evgeny。我收到错误 3085 - 未定义的函数合并
  • 好吧,可能vba没有这个功能。如果您确定sum 不能是null,那么您可以删除coalesce。离开Select Sum(t2.Col1) + Sum(t2.Col2)
  • 不幸的是也不起作用!希望 Excel 和 Access 一样大!我本可以在几秒钟内完成
【解决方案2】:

一种方法使用相关子查询:

select col1, col2, col3,
       (select sum(tt1.col1) + sum(tt1.col2)
        from table1 as tt1
        where tt1.col3 = t1.col3
       ) as Total
from table1 as t1;

如果你想以update的身份这样做,也是一样的想法:

update table1
    set Total = (select sum(tt1.col1) + sum(tt1.col2)
                 from table1 as tt1
                 where tt1.col3 = table1.col3
                );

【讨论】:

  • 谢谢戈登。如果我使用您的代码“操作必须使用可更新查询”,我会收到运行时错误 3073
猜你喜欢
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
  • 2018-07-30
  • 2019-06-08
  • 2014-05-04
  • 1970-01-01
相关资源
最近更新 更多