如何检索迄今为止的季度和年度值

how to retrieve quarter and year values to date

我正在使用下面的table:

期间 费用 产品
2019 年 1 月 11 日 德国 1.54 产品 1
2019 年 1 月 11 日 美国 2.35 产品 1
2019 年 1 月 11 日 德国 4.21 产品 2
2019 年 1 月 11 日 美国 0.87 产品 2
2019 年 1 月 12 日 德国 1.456 产品 1
2020 年 1 月 1 日 德国 5.3 产品 2
2020 年 1 月 2 日 美国 9.76 产品 1
2020 年 1 月 3 日 德国 6.78 产品 1
2020 年 1 月 3 日 美国 1.2 产品 2
2020 年 1 月 3 日 德国 3.964 产品 2
2020 年 1 月 4 日 美国 2.58 产品 1
2020 年 1 月 4 日 美国 2.8 产品 2
2020 年 1 月 4 日 德国 0.5 产品 1

要测试的代码:

    CREATE OR REPLACE TEMPORARY TABLE "TMP_TEST" (
        "Period"  DATE,
        "Country"     VARCHAR,
        "Cost"    FLOAT,
        "Product"    VARCHAR
    );
    
    INSERT INTO "TMP_TEST" 
    VALUES 
('01/11/2019','DE','1.54','Product1'),
('01/11/2019','US','2.35','Product1'),
('01/11/2019','DE','4.21','Product2'),
('01/11/2019','US','0.87','Product2'),
('01/12/2019','DE','1.456','Product1'),
('01/01/2020','DE','5.3','Product2'),
('01/02/2020','US','9.76','Product1'),
('01/03/2020','DE','6.78','Product1'),
('01/03/2020','US','1.2','Product2'),
('01/03/2020','DE','3.964 ','Product2'),
('01/04/2020','US','2.58','Product1'),
('01/04/2020','US','2.8','Product2'),
('01/04/2020','DE','0.5 ','Product1');

select * from TMP_TEST;

WITH TOTAL AS (
    SELECT
        "Period","Country","Cost","Product"
    FROM "TMP_TEST"
)
SELECT
    TOTAL.*,
    IFF(UPPER("Country") = 'DE', "Cost", 0) as "Cost DE",
    IFF(UPPER("Country") = 'US', "Cost", 0) as "Cost US",
    DATEADD(MONTH, -1, "Period") AS "Period M-1",
    LAG("Cost", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost USD M1",
    LAG("Cost DE", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost DE M1",
    LAG("Cost US", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost US M1"
FROM TOTAL

现在我想要相同的结果,为当前季度的产品总成本添加一列(假设我们在 2020 年 1 月 2 日期间,我想要产品季度的累计总和(包括 1 月和 2 月) ))

WITH TOTAL AS (
    SELECT
        "Period","Country","Cost","Product"
    FROM "TMP_TEST"
)
SELECT
    DATE_TRUNC('Q',"Period") AS "Quarter",  -- New Quarter Column added for Quarter
    TOTAL.*,
    IFF(UPPER("Country") = 'DE', "Cost", 0) as "Cost DE",
   IFF(UPPER("Country") = 'US', "Cost", 0) as "Cost US",
    DATEADD(MONTH, -1, "Period") AS "Period M-1",
   LAG("Cost", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost USD M1",
   LAG("Cost DE", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost DE M1",
   LAG("Cost US", 1, 0) OVER (PARTITION BY "Country", "Product" ORDER BY "Period") AS "Cost US M1",
   SUM("Cost") OVER (PARTITION BY "Country", "Product","Quarter" ORDER BY "Period") AS"Quarter Cost", -- New Column added For Aggregation By Quarter TO Date

   SUM("Cost DE") OVER (PARTITION BY "Country", "Product","Quarter" ORDER BY "Period") AS"Quarter Aggregation Cost DE" -- New Column added For Aggregation By Quarter TO Date
 
FROM TOTAL;