困难的部分是所有产品可能在日期之前和日期之间都没有收入。在这些情况下,这将返回 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