0

我有两个表,表 1:

Col1_1  Col1_2
A       X
B       Y
C       Z

表 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定义条件。

任何建议表示赞赏!谢谢!

4

1 回答 1

1

您需要将 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
于 2018-06-15T18:30:42.750 回答