Sql 使用同一表中现有行的总和插入新行
我正在写一个SQL脚本,我有这个表 我想用这个结果更新表,插入一个新行 当类型为1时,有此公式Sql 使用同一表中现有行的总和插入新行,sql,sum,sql-insert,Sql,Sum,Sql Insert,我正在写一个SQL脚本,我有这个表 我想用这个结果更新表,插入一个新行 当类型为1时,有此公式8类型1=7-(1+2+3+4+5+6) 我怎样才能做到呢 谢谢。你在找这样的东西吗 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',
8类型1=7-(1+2+3+4+5+6)
我怎样才能做到呢
谢谢。你在找这样的东西吗
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
使用条件聚合,将七个值相加为正值,将其他值相加为负值:
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;
您的公式将产生-14。金额列必须显示绝对值:)请不要将图像用于数据-使用格式化/表格文本。请给我们看看你尝试了什么,并解释你在哪里卡住了。好的@DaleK感谢您的反馈:)