SQL Pivot表CTE和Order生成Null值

时间:2017-04-17 20:15:09

标签: sql sql-server pivot common-table-expression

我正在努力让以下工作,我是Pivot表的新手,我以为我有它,但我得到了很多空值。我错过了什么?另外,我可以在哪里插入ORDER BY子句来对NUM进行排序。

 with cte_Inst as
 (

    SELECT     Inst.Num, Branch.BranchNum, 
    inst.Name as 'InstName', Center.ProfitCenter, 
    Center.plant, Branch.Idx, Inst.Enable,Inst.BranchBilling, mainframe.Name as 'Host', center.Name as 'Center'
    FROM         Center RIGHT OUTER JOIN
                      mainframe ON Center.Idx = mainframe.CenterIdx RIGHT OUTER JOIN
                      DB ON mainframe.Idx = DB.MainframeIdx RIGHT OUTER JOIN
                      Inst ON DB.DBIdx = Inst.DBIdx RIGHT OUTER JOIN
                      Branch ON Inst.Idx = Branch.InstIdx
    where BranchNum = 999999
    --order by Num, BranchNum 

  )

select num, PRB575  as 'PRB575', PRB576 as 'PRB576', PRB577 as 'PRB577', PRB578 as 'PRB578', PRB579 as'PRB579',PRB580 as'PRB580', PRB572 as 'PRB572', PRB573 as 'PRB573',PRB851 as'PRB851', PRB581 as 'PRB581', PRB582 as 'PRB582',PRB583 as'PRB583'
From 
(                     
            SELECT     InputCounts.Count as 'Total', InputCounts.DateTime, cte_Inst.num, --cte_Inst.InstName,  
        InputDesc.ShortName,   
                              Material.FoundationMaterialNumber, cte_inst.host,  cte_Inst.Center   
        FROM        cte_Inst 
                    left OUTER JOIN InputCounts on InputCounts.BranchIdx = cte_Inst.Idx 
                    left outer join PhysicalSource on InputCounts.PhysicalSourceIdx = PhysicalSource.Idx  
                    left outer join InputDesc ON  InputDesc.Idx = inputcounts.inputdescidx 
                    left OUTER JOIN Material ON InputDesc.MaterialIdx = Material.Idx
                    WHERE     ( (cte_Inst.Enable ='true')   
                              and (InputCounts.DateTime > '2017-03-28')
                              and FoundationMaterialNumber in  ('PRB575','PRB576','PRB577','PRB578','PRB579','PRB580','PRB572','PRB573','PRB851','PRB581','PRB582','PRB583')
                              ))
                      As SourceDataTable
Pivot
(
Max(Total) for FoundationMaterialNumber in (PRB575, PRB576, PRB577,PRB578,PRB579,PRB580,PRB572,PRB573,PRB851,PRB581,PRB582,PRB583))
as pivottable

转轴前的原始数据集 Before Pivot

在Pivot之后 After Pivot

0 个答案:

没有答案