在SQL Server中,如何使行作为列?

Lia*_*san 1 sql sql-server stored-procedures

我有2张桌子

产品过去

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
Run Code Online (Sandbox Code Playgroud)

产品电流

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
Run Code Online (Sandbox Code Playgroud)

预期产量

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
Run Code Online (Sandbox Code Playgroud)

我试图在存储过程中像下面那样创建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
Run Code Online (Sandbox Code Playgroud)

但我没有得到确切的结果。

Tim*_*sen 5

实际上,这里似乎需要一个完全外部联接:

SELECT
    COALESCE(pp.productID, pc.productID) AS productID,
    COALESCE(pp.deptID, pc.deptID) AS deptID,
    COALESCE(pp.month, pc.month) AS Month,
    COALESCE(pp.year, 2015) AS PrevYear,
    COALESCE(pp.price, 0) AS PrevPrice,
    COALESCE(pc.year, 2016) AS CurrYear,        
    COALESCE(pc.price, 0) AS CurrPrice
FROM ProductPast pp
FULL OUTER JOIN ProductCurrent pc
    ON pp.productID = pc.productID AND
       pp.deptID = pc.deptID AND
       pp.year = pc.year - 1 AND
       pp.month = pc.month
ORDER BY
    COALESCE(pp.productID, pc.productID),
    COALESCE(pp.deptID, pc.deptID),
    COALESCE(pp.month, pc.month);
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

演示版

请注意,执行此操作的另一种方法是使用包含所有年份和月份的日历表(可能还包含产品和部门)。然后,您可以执行一系列常规的内部/左联接以获得所需的结果。