使用来自相同 table 的现有行的总和插入新行
INSERT new row by using sum of existing rows from same table
我正在编写一个 SQL 脚本并且我有这个 table
我想更新table插入一个新行这个结果
有这个公式EIGHT TYPE 1= SEVEN-(ONE+TWO+THREE+FOUR+FIVE+SIX) when TYPE = 1
如何实现?
谢谢。
您在找这样的东西吗?
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;
我正在编写一个 SQL 脚本并且我有这个 table
我想更新table插入一个新行这个结果
有这个公式EIGHT TYPE 1= SEVEN-(ONE+TWO+THREE+FOUR+FIVE+SIX) when TYPE = 1
如何实现?
谢谢。
您在找这样的东西吗?
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;