【问题标题】:Current Year Sales and Previous Year Sales in the same table?同一张表中的当年销售额和上一年销售额?
【发布时间】:2020-02-06 02:27:16
【问题描述】:

早安,

我希望将同一周的“上一年销售额”添加到 Teradata 拉取中,但我在编码方面失败了。我为获得该周/年的销售额而编写的基线是:

SELECT a."WEEK_NBR" AS "YearWeek"
, SUM(a."Sales") AS "CurrentYearSales"

FROM "SALESTABLE" AS a

这会导致:

YearWeek  CurrentYearSales

201901    $7,499

201902    $2,300

201903    $6,360


...

202001    $4,500

202002    $9,000

202003    $8,500

如果数据表中有前一年,我希望能够在同一行显示前一年的销售额。这样完成后的表格将如下所示:

YearWeek  CurrentYearSales PriorYearSales

201901    $7,499           NULL

201902    $2,300           NULL

201903    $6,360           NULL
...

202001    $4,500           $7,499

202002    $9,000           $2,300

202003    $8,500           $6,360

当我搜索时,我能找到的只是如何处理本周的数据,但是这对表中的所有记录都可以吗?

【问题讨论】:

    标签: datetime teradata


    【解决方案1】:

    编辑:当您汇总数据时,您需要在 加入之前聚合。

    假设WEEK_NBR 是数字,您需要一个自联接:

    with cte as 
     (
       SELECT a."WEEK_NBR" AS "YearWeek"
        , SUM(a."Sales") AS "CurrentYearSales"
       FROM "SALESTABLE" AS a
       group by 1
     )
    select ...
    from cte as t1
    left join cte as t2
    on t2.YearWeek = t1.Ye arWeek- 100
    

    正如@Andrew 所指出的,这也适用于字符串,因为当您将数字添加到字符串或比较数字和字符串时,Teradata 会对浮点数进行自动类型转换(不过我更喜欢编写显式类型转换)

    【讨论】:

    • 无论好坏,如果 week_nbr 为 char 或 varchar,Teradata 将在此处进行隐式转换。
    • 抱歉,省略号在哪里? (还编辑了用 t1 替换 a 的查询?)用 cte 作为( SELECT t1."WEEK_NBR" AS "YearWeek" , SUM(t1."Sales") AS "CurrentYearSales" FROM "SALESTABLE" group by 1 )选择 SUM(t2 ."Sales") AS "PriorYearSales" from cte as t1 left join cte as t2 on t2.WEEK_NBR = t1.WEEK_NBR - 100
    • 选择类似于select t1.week_nbr as yearweek, t1.CurrentYearSales as CurrentYearSales, t2.CurrentYearSales as PrevYearSales from...
    • 我收到Executed as Single statement. Failed [5628 : HY000] Column WEEK_NBR not found in t2 or t1. Elapsed time = 00:00:00.568 STATEMENT 1: WITH failed.
    • 您在 CTE 中对其进行了重命名。使用 t1.YearWeek 而不是 t1.Week_Nbr。
    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2021-01-16
    • 2022-10-04
    相关资源
    最近更新 更多