【问题标题】:INSERT new row by using sum of existing rows from same table使用同一表中现有行的总和插入新行
【发布时间】:2021-03-25 18:40:26
【问题描述】:

我正在编写一个 SQL 脚本,我有这张表

我想用这个结果更新表格插入一个新行

有这个公式EIGHT TYPE 1= SEVEN-(ONE+TWO+THREE+FOUR+FIVE+SIX) when TYPE = 1

我怎样才能实现它?

谢谢。

【问题讨论】:

  • 你的公式会产生 -14。
  • 金额栏必须显示绝对值:)
  • 请不要使用图像作为数据 - 使用格式化/表格文本。请向我们展示您的尝试并解释您遇到的问题。
  • 好的! @DaleK 感谢您的反馈:)

标签: sql sum sql-insert


【解决方案1】:

使用条件聚合将 SEVEN 值相加为正数,其他值为负数:

insert into mytable (company, kpi, date, location, type, amount)
  select 
    2, 'EIGHT TYPE1', 202101, 1, null,
    sum(case when kpi = 'SEVEN' then amount else -amount end)
  from mytable
  where type = 1;

【讨论】:

    【解决方案2】:

    你在寻找这样的东西吗?

    select company, kpi, date, location, type, amount
    from t
    union all
    select company, 'EIGHT', date, location, NULL as type,
           sum(case when kpi in ('ONE', . . . ) then amount
                    when kpi in ('SEVEN') then -amount
               end)
    from t
    where type = 1
    group by company, date, location
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多