将多个表格与Teradata

时间:2018-02-07 08:58:59

标签: teradata

我试图将3个不同的表组合成一个具有特定标准的表。

  1. 表2 - 根据出货单号和出货日期计算出货总重量
  2. 表3 - 根据托运人编号和发货日期计算总收入金额
  3. 结果 - 将表合并到一个表中。
  4. 此外,SQL还应该过滤" Customer Since" < = 720和"发货日期" < = 360

    (注:客户编号=发货人编号)

    enter image description here

1 个答案:

答案 0 :(得分:0)

很难说出你在寻找什么,但这可以让你开始

SELECT t2.Shipper_Number, t2.Ship_Date, t2.Total_Weight, t3.Total_Revenue
FROM (
  SELECT Shipper_Number, Ship_Date, SUM(Weight) AS Total_Weight
  FROM Table2
  GROUP BY Shipper_Number, Ship_Date
) t2
INNER JOIN (
  SELECT Shipper_Number, Ship_Date, SUM(Revenue) AS Total_Revenue
  FROM Table3
  GROUP BY Shipper_Number, Ship_Date
) t3 ON t2.<PK_column> = t3.<PK_column>

一些注意事项:

  • INNER JOIN只返回两个表中匹配的行
  • 您可以在子查询中将"Customer Since""Ship Date"条款添加为WHERE条款

<强>更新
如果您希望每个(Shipper_Number, Ship_Date)组获得一行,那么您需要使用该列组合(JOIN)为这两个派生表制定Shipper_Number, Ship_Date条件。

如果您想进一步过滤"Customer Since"上的行,那么只需JOIN到源表并添加过滤条件。像这样:

SELECT t2.Shipper_Number, t2.Ship_Date, t2.Total_Weight, t3.Total_Revenue
FROM (
  SELECT Shipper_Number, Ship_Date, SUM(Weight) AS Total_Weight
  FROM Table2
  WHERE Ship_Date <= Ship_Date - INTERVAL '360' DAY -- Assumes you want only order that shipped within the last 360 days
  GROUP BY Shipper_Number, Ship_Date
) t2
INNER JOIN (
  SELECT Shipper_Number, Ship_Date, SUM(Revenue) AS Total_Revenue
  FROM Table3
  WHERE Ship_Date <= Ship_Date - INTERVAL '360' DAY -- Assumes you want only order that shipped within the last 360 days
  GROUP BY Shipper_Number, Ship_Date
) t3 ON t2.Shipper_Number = t3.Shipper_Number AND t2.Ship_Date = t3.Ship_Date
INNER JOIN Table1 t1 ON t2.Shipper_Number = t1.Customer_Number -- Get shipper/customer info
WHERE t1."Customer Since" <= "Customer Since" - INTERVAL '720' DAY -- Assuming you want to get customers that are fewer than 720 days old

同样,使用INNER JOIN,这假设在(Shipper_NumberShip_Date)的两个表中都存在匹配的行,否则它将不会返回该行。

此外,如果可行,您可以考虑根据公共密钥(t2)或t3shipper_number, shipping_numbershipping_number表合并到一个表中如果它是一个独特的价值。