我在雪花中有这段代码来获取下表:
CREATE OR REPLACE TABLE LIVE_ANALYTICS.REPORTING."GL_REPORT"
AS
SELECT
SUM("TABLE_GL_ENTRY"."Amount" AS "AMOUNT",
MONTH("TABLE_GL_ENTRY"."Posting Date") AS "MONTH",
YEAR("TABLE_GL_ENTRY"."Posting Date") AS "YEAR",
"TABLE_GL_ENTRY"."Global Dimension 1 Code" AS "ID_STORE",
CASE
WHEN "YEAR" = YEAR(CURRENT_DATE()) THEN 'AMOUNT_CURRENT_YEAR'
ELSE 'AMOUNT_LAST_YEAR'
END AS "METRIC"
FROM
LIVE_ANALYTICS.NAVISION."G_L Entry" AS "TABLE_GL_ENTRY"
WHERE
(("MONTH" = MONTH(CURRENT_DATE()) OR "MONTH" = MONTH(ADD_MONTHS(CURRENT_DATE, 1)))
AND
("YEAR" = YEAR(CURRENT_DATE()) OR "YEAR" = YEAR(ADD_MONTHS(CURRENT_DATE, -12))))
AND
(("ID_STORE" LIKE '1')
OR
("ID_STORE" LIKE '2')
OR
("ID_STORE" LIKE '3'))
GROUP BY
MONTH",
"YEAR",
"ID_STORE",
;
仅当 "YEAR" = 2021 时,我才需要从该表中减去 "MONTH" 和 "ID_STORE" 的 "AMOUNT" 。
AMOUNT_CURRENT_YEAR - AMOUNT_LAST_YEAR
最后,我想将这些新结果与其他现有记录一起插入到现有表中。
我怎样才能做到这一点?有什么建议吗?
先感谢您
亲切的问候。
编辑:这是我前几天搜索的解决方案,谢谢大家!
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=9909600b9ac804ba67b7086c40e0c844
create table last_amount as
select sum(amount) as 'amount_last', month, year, id, metric
from data where metric like 'last'
group by month, year, id, metric
order by id, month, year;
create table current_amount as
select sum(amount) as 'amount_current', month, year, id, metric
from data where metric like 'current'
group by month, year, id, metric
order by id, month, year
create table subtract as
select
c.amount_current - l.amount_last as amount, c.month, c.year, c.id
from
last_amount l
join
current_amount c
on
l.id = c.id
and
l.month = c.month;
alter table subtract add metric varchar(255) default 'subtract';
insert into data
select * from subtract;
drop table last_amount;
drop table current_amount;
select * from data order by id, month, year;