同一表中的当年销售额和上一年销售额?

时间:2020-02-05 15:08:07

标签: datetime teradata

早上好

我希望将“上一年度的销售额”添加到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

搜索时,我只能找到如何使用当前周的数据来执行此操作,但是对于表中的所有记录都可以做到这一点吗?

1 个答案:

答案 0 :(得分:0)

编辑:汇总数据后,需要在连接之前 进行汇总。

您需要进行自我联接,假设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会自动对浮点型进行类型转换(尽管我更愿意编写显式类型强制转换)< / p>