具有多列的未透明数据 - 请提供语法帮助

时间:2014-07-18 04:21:40

标签: sql sql-server-2008 unpivot

我有以下数据,我想将其取消

enter image description here

我创建了此查询以取消对“实际”'行但似乎无法找出解开'计划'的方法。和' PriorYear'同样。

SELECT FiscalYear, Period, MetricName, ActualValue
FROM vw_ExecSummary
UNPIVOT
(ActualValue FOR MetricName IN ( [Net Revenue], [Total C.S. Salaries]
)) AS unpvt  
WHERE [Type] = 'Actual'

不透明的数据看起来像这样,但我还要将Plan和PriorYear列添加到下面ActualValue列的右侧

enter image description here

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:0)

这是Itzig Ben-Gan's cross apply values pivoting的情况:

create table #data (FiscalYear smallint, Period tinyint, ValueType nvarchar(25), NetRevenue float, Salaries float);
insert into #data values 
    (15,1,N'Actual',3676798.98999,1463044.71999),
    (15,1,N'Plan',3503920.977405,1335397.32878),
    (15,1,N'PriorYear',4043634.449,1543866.89);

select  d.FiscalYear, d.Period,
        ActualNetRevenue = sum(v.ActualNetRevenue), ActualSalaries = sum(v.ActualSalaries),
        PlanNetRevenue = sum(v.PlanNetRevenue), PlanSalaries = sum(v.PlanSalaries),
        PriorYearNetRevenue = sum(v.PriorYearNetRevenue), PriorYearSalaries = sum(v.PriorYearSalaries)
from    #data d
cross apply
        (values
        (N'Actual',d.NetRevenue,d.Salaries,0,0,0,0),
        (N'Plan',0,0,d.NetRevenue,d.Salaries,0,0),
        (N'PriorYear',0,0,0,0,d.NetRevenue,d.Salaries))
        v (ValueType, ActualNetRevenue, ActualSalaries, PlanNetRevenue, PlanSalaries, PriorYearNetRevenue, PriorYearSalaries)
where   d.ValueType = v.ValueType
group by d.FiscalYear, d.Period;

drop table #data;