SQL Sum收入和第二个表中的日期

时间:2013-10-16 22:28:31

标签: sql join sum

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

表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。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分: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