我试图将3个不同的表组合成一个具有特定标准的表。
答案 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>
一些注意事项:
"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_Number
和Ship_Date
)的两个表中都存在匹配的行,否则它将不会返回该行。
此外,如果可行,您可以考虑根据公共密钥(t2
)或t3
将shipper_number, shipping_number
和shipping_number
表合并到一个表中如果它是一个独特的价值。