如何在PIVOT查询中动态添加列

时间:2018-10-08 06:33:15

标签: sql sql-server

我有一个#temp表,其中的数据类似于[这不是实际数据,但与此类似],我已经使用动态PIVOT填充了该数据

Name      Department  Div   Science Maths  Bio
Prashant    CSE        A    20      NULL   NULL
Prashant    CSE        A    NULL    50     NULL
Lisa       CBSE        A    11      NULL   NULL
Lisa       CBSE        A    NULL    90     NULL
Lisa       CBSE        A    NULL    NULL   56

所以我想要的是

Name      Department    Div Science Maths   Bio
Prashant    CSE         A   20      50     NULL
Lisa       CBSE         A   12      90     56

我使用的动态SQL [实际查询产生的输出类似于第一个表:

SET @DynamicPivotQuery = 
    N'SELECT departmentName as Department,EmployeeCode as EmpCode,
    designationName as Designation,employeeName as EmployeeName,NatureofActivity,
       oversightCode,'+@selectCols+'
    INTO ##TempPivot
    FROM #OVERSIGHTANDCOETABLE
    PIVOT(SUM(percentage) 
          FOR name IN (' + @cols + ')) AS PVTTable PIVOT
          (
          MAX(OversightFunction) 
          FOR name1 IN (' + @displayCols + ')) AS PVTTable1'

3 个答案:

答案 0 :(得分:2)

尝试此选项:

WITH cte AS (
    -- your current dynamic query
)

SELECT
    Name,
    Department, 
    Div,
    MAX(Science) AS Science,
    MAX(Maths) AS Maths,
    MAX(Bio) AS Bio
FROM cte
GROUP BY
    Name,
    Department, 
    Div;

答案 1 :(得分:1)

您可以使用aggregate functions来获取所需的输出

 select Name,max(Department), max(Div), max(Science),max( Maths) ,max(  Bio)
    from table
    group by Name

答案 2 :(得分:0)

create table temp
(
    date datetime,
    category varchar(3),
    amount money
)

insert into temp values ('1/1/2012', 'ABC', 1000.00)
insert into temp values ('2/1/2012', 'DEF', 500.00)
insert into temp values ('2/1/2012', 'GHI', 800.00)
insert into temp values ('2/10/2012', 'DEF', 700.00)
insert into temp values ('3/1/2012', 'ABC', 1100.00)


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT date, ' + @cols + ' from 
            (
                select date
                    , amount
                    , category
                from temp
           ) x
            pivot 
            (
                 max(amount)
                for category in (' + @cols + ')
            ) p '