1

我有两个表,我试图将它们组合起来以返回第二个表中定义的两个日期之间的收入数据。

表格1

Product     Date         Revenue
A           01/01/2013   300
A           02/01/2013   400
A           03/01/2013   500
B           04/01/2013   100
B           08/01/2013   400
C           04/01/2013   800
C           10/01/2013   900

表 2

 Product    Date1         Date2
    A          02/01/2013    04/01/2013
    B          05/01/2013    07/01/2013
    C          01/01/2013    11/01/2013

我需要加入这些表格,以便获得日期之间和第一个日期之前的收入总和。所以我希望结果表看起来像这样

表3

Product    Revenue1    Date1       Revenue2     Date2
A          300         02/01/2013  900          04/01/2013
B          100         05/01/2013  400          07/01/2013
C          0           01/01/2013  1700         11/01/2013

我正在使用teradata。任何帮助,将不胜感激

4

1 回答 1

1

困难的部分是所有产品可能在日期之前和日期之间都没有收入。在这些情况下,这将返回 NULL,但如果你想要其他东西,你可以使用 COALESCE/ISNULL。

WITH RevenueBeforeDate1 AS (
    SELECT Table1.Product
          ,Table2.Date1
          ,Table2.Date2
          ,SUM(Table1.Revenue) AS SumRevenue
    FROM Table1
         INNER JOIN Table2
             ON Table1.Product = Table2.Product
    WHERE Table1.Date < Table2.Date1
    GROUP BY Table1.Product
            ,Table2.Date1
            ,Table2.Date2
)
,RevenueBetweenDates AS (
    SELECT Table1.Product
          ,Table2.Date1
          ,Table2.Date2
          ,SUM(Table1.Revenue) AS SumRevenue
    FROM Table1
         INNER JOIN Table2
             ON Table1.Product = Table2.Product
    WHERE Table1.Date BETWEEN Table2.Date1 AND Table2.Date2
    GROUP BY Table1.Product
            ,Table2.Date1
            ,Table2.Date2
)
SELECT COALESCE(RevenueBeforeDate1.Product, RevenueBetweenDates.Product) AS Product
      ,RevenueBeforeDate1.SumRevenue AS Revenue1
      ,COALESCE(RevenueBeforeDate1.Date1, RevenueBetweenDates.Date1) AS Date1
      ,RevenueBetweenDates.SumRevenue AS Revenue2
      ,COALESCE(RevenueBeforeDate1.Date2, RevenueBetweenDates.Date1) AS Date2
FROM RevenueBeforeDate1
     FULL OUTER JOIN RevenueBetweenDates
         ON RevenueBeforeDate1.Product = RevenueBetweenDates.Product

编辑
对过于复杂的代码感觉有点不好。回复快。

这是一个更清洁的解决方案

SELECT Table2.Product
      ,SUM(RevenueBeforeDate1) AS Revenue1
      ,Table2.Date1
      ,SUM(RevenueBetweenDates) AS Revenue2
      ,Table2.Date2
FROM Table2
     LEFT JOIN Table1
         ON Table2.Product = Table1.Product
     CROSS APPLY (
         SELECT CASE WHEN Table1.Date < Table2.Date1
                     THEN Table1.Revenue
                     ELSE NULL
                END AS RevenueBeforeDate1
               ,CASE WHEN Table1.Date BETWEEN Table2.Date1 AND Table2.Date2
                     THEN Table1.Revenue
                     ELSE NULL
                END AS RevenueBetweenDates
     )
GROUP BY Table2.Product
        ,Table2.Date1
        ,Table2.Date2
于 2013-10-16T22:43:25.013 回答