如何连接 teradata 中的两个表,其中输出列是根据条件计算的?

How can I join two tables in teradata in which the output columns are calculated based on a condition?

我有两个table, Table 1 :

Col1_1  Col1_2
A       X
B       Y
C       Z

Table 2 :

Col2_1  Col2_2  Col2_3     Col2_4
A          X    6/20/2018   10
B          Y    8/13/2018   20
C          Z    6/27/2018   10
A          X    8/13/2018   40
B          Y    9/3/2018    80
C          Z    12/1/2018   5

这是我正在寻找的输出(今天的日期是 6/18/2018):

Col1_1  Col1_2  Sum of Col2_4 between today and (today + 5 days)    Sum of Col2_4  between (today + 5 days) and (today + 10 days)
A            X                          10                                   0
B            Y                           0                                   0
C            Z                           0                                  10

这是我目前在 teradata 中的代码:

SELECT 
Col1_1,
Col1_2, 
Case 
    WHEN Col2_3 > CURRENT_DATE and Col2_3 < CURRENT_DATE+5
    THEN SUM (Col2_4)
    ELSE '0'
    End as Calculated_Col_1,

Case 
    WHEN Col2_3 > CURRENT_DATE+5 and Col2_3 < CURRENT_DATE+10
    THEN SUM (Col2_4)
    ELSE '0'
    End as Calculated_Col_2, 

FROM Table1 as A

INNER JOIN Table2 as B
ON A.Col1_1 = B.Col2_1 
AND A.Col1_2 = B.Col2_2

WHERE -- ? ?

我对如何在 SELECT 语句中定义列名称以及如何定义 WHERE 条件感到困惑。

如有任何建议,我们将不胜感激!谢谢!

您需要将 SUM 移到 CASE 之外,并在 HAVING 中应用计算列的条件:

SELECT 
Col1_1,
Col1_2, 
SUM(Case 
      WHEN Col2_3 > CURRENT_DATE and Col2_3 < CURRENT_DATE+5
      THEN Col2_4
      ELSE 0
    End) as Calculated_Col_1,

SUM(Case 
      WHEN Col2_3 > CURRENT_DATE+5 and Col2_3 < CURRENT_DATE+10
      THEN Col2_4
      ELSE 0
    End as Calculated_Col_2, 

FROM Table1 as A

INNER JOIN Table2 as B
ON A.Col1_1 = B.Col2_1 
AND A.Col1_2 = B.Col2_2

HAVING Calculated_Col_1 > 1111 -- ot whatever