pivot或un pivot sql server2005

时间:2018-02-05 10:27:04

标签: sql-server

My Pivot

SELECT *
FROM
(
    SELECT projectallocation.proAllocationID AS Sno,
           temp.intro_name AS IntroTop,
           projectallocation.introtoplevelEmpid AS TopEmp,
           (companystructure.csshortname) AS Level,
           introducermaster.intro_name AS IntroLow,
           projectallocation.introlevelEmpid AS EmpID
    FROM projectallocation
         INNER JOIN dbo.IntroducerMaster ON dbo.introducermaster.empid = projectallocation.introLevelEmpid
         INNER JOIN introducermaster AS temp ON temp.empiD = projectallocation.introtopLevelEmpid
         INNER JOIN companyStructure ON companyStructure.HLevel = projectallocation.introleveID
    WHERE projectallocation.projectID = 1
          AND projectallocation.introleveID = 4
    GROUP BY IntroducerMaster.Intro_Name,
             temp.intro_name,
             companyStructure.CSShortName,
             projectallocation.proAllocationID,
             projectallocation.introlevelEmpid,
             projectallocation.introtoplevelEmpid,
             projectallocation.introtoplevelid
) b PIVOT(MAX(introlow) FOR level IN(ch,
                                     ed,
                                     dir,
                                     gm,
                                     agm,
                                     bdm,
                                     smm)) PVT;

输出

sno   Introtop  topempid  empid  ch     ed    dir  gm  agm  bdm    smm
---------------------------------------------------------------------
1     Jhon.A     emp01    emp05  null  null  null  null null ajju.R  null

输出有49行我只包含一行......

我想要

sno   Introtop  topempid    ch     ed    dir  gm  agm  bdm    smm    empid
--------------------------------------------------------------------------
1     Jhon.A     emp01      null  null  null  null null ajju.R  null  emp005

empid应该是最后请帮助我!!!!

1 个答案:

答案 0 :(得分:3)

解决方案很简单,更改SELECT *并以您希望的任何顺序将*替换为列名。

喜欢这个

SELECT
    sno,
    Introtop,
    topempid,
    ch,
    ed,
    dir,
    gm,
    agm,
    bdm,
    smm,
    empid
    FROM