转置表与信息

时间:2016-05-19 00:42:42

标签: sql sql-server transpose

我需要转换此视图(在sql中)

enter image description here

进入这个观点:

enter image description here

任何解决方案?

2 个答案:

答案 0 :(得分:0)

您可以使用union all

select location, planning_product, '2016-05-16' as MondayDate, [5/16/2016] as ROP
from t
union all
select location, planning_product, '2016-05-09' as MondayDate, [5/9/2016] as ROP
from t
union all
. . .

请注意,列名称需要进行转义。有些数据库使用双引号,其他数据库使用反引号或方括号。

答案 1 :(得分:0)

我们假设表名是 Tab 并且您有以下3个日期(您可以用自己的日期替换它们):[1/16/2015],[2 / 16/2015],[2015年3月16日]

WITH Unpivoted (PlanningProduct, Location, [Monday Date], ROP)
AS(
    SELECT PlanningProduct, Location, CONVERT(datetime,MondayDate) AS [Monday Date], ROP
    FROM 
        (SELECT Location, PlanningProduct, [1/16/2015], [2/16/2015], [3/16/2015] -- add your dates
        FROM Tab) pvt
    UNPIVOT
        (ROP FOR MondayDate IN ([1/16/2015], [2/16/2015], [3/16/2015])) AS unpvt -- add your dates
)
SELECT PlanningProduct, Location, [Monday Date], SUM(ROP) AS ROP
FROM Unpivoted
GROUP BY PlanningProduct, Location, [Monday Date]