我有2张桌子
ProductPast
productID deptID year month price
-------------------------------------------
1 10 2015 1 45
1 10 2015 2 65
2 11 2015 1 45
2 11 2015 2 65
2 11 2015 3 44
ProductCurrent
productID deptID year month price
-------------------------------------------
1 10 2016 1 12
1 10 2016 2 46
1 10 2016 3 77
2 11 2016 1 88
预期产量
productID deptID Month PrevYear PrevPrice CurrYear CurrPrice
-----------------------------------------------------------------------------------------
1 10 1 2015 45 2016 12
1 10 2 2015 65 2016 46
1 10 3 2015 0 2016 77
2 11 1 2015 45 2016 88
2 11 1 2015 65 2016 0
2 11 1 2015 44 2016 0
我试图在存储过程中像下面那样创建unionall和group
SELECT ProductID,DeptID,month
into #rec
FROM (
SELECT ProductID,DeptID,year,month FROM ProductPast
UNION ALL
SELECT ProductID,DeptID,year,month FROM ProductCurrent
)
group by ProductID,DeptID,month
SELECT ProductID,DeptID,month,p.year as PrevYear, c.year as CurrYear, p.price as prevprice,c.price as currprice
FROM rec
LEFT JOIN ProductPast p on p.productid = rec.productID and p.month = rec.month
LEFT JOIN ProductCurrent c on c.productid = rec.productID and c.month = rec.month
但是我没有得到确切的结果。
答案 0 :(得分:5)
实际上,在这里您似乎需要完全外部联接:
SSL_CERT_DIR
请注意,执行此操作的另一种方法是使用包含所有年份和月份(可能还有产品和部门)的日历表。然后,您可以执行一系列常规的内部/左联接以获得所需的结果。