1

我有一个销售表,显示每周的产品编号、销售价值和销售量。我需要构建一个报告来显示这些值和数量以及前一周的等效值。我还有一个 Weeks 表,它为我提供了当前周的前一周编号(例如,如果当前周是 2013-01,那么前一周的值是 2012-52)。

因此,我认为从 Weeks 表中加入另一个有关产品编号和前一周编号的 Sales 实例会很简单。但是 Teradata 不允许我这样做,最初它抛出了一个错误,Improper column reference in the search condition of a joined table当我重新排序查询以引用 Sales 的第二个实例之前的 Weeks 时,它现在尝试运行但给了我一个No more spool space错误,所以我认为我的方法不正确. 我的SQL如下:

select s.Week_Number,
       s.Product_Number,
       s.Sales_Value,
       s.Sales_Volume,
       s_lw.Sales_Value,
       s_lw.Sales_Volume

   from SALES s
  inner join WEEKS w 
     on s.Week_Number = w.Week_Number
   left join SALES s_lw 
     on     s.Product_Number = s_lw.Product_Number
        and s_lw.Week_Number = w.Last_week_Number

谁能建议我在这里做错了什么?看来这应该是可以实现的。

4

1 回答 1

1

我建议使用 Window Aggregate Function 通过SALES表的单次传递来完成此操作:

SELECT DISTINCT
       s.Week_Number,
       s.Product_Number,
       s.Sales_Value,
       s.Sales_Volume,
       MAX(s.Sales_Value) OVER (PARTITION BY s.Product_Number 
                                    ORDER BY s.Week_Number DESC 
                                ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS LW_Sales_Value,
       MAX(s.Sales_Volume) OVER (PARTITION BY s.Product_Number
                                    ORDER BY s.Week_Number DESC 
                                ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS LW_Sales_Volume
  FROM SALES s;
于 2013-06-01T02:15:46.503 回答