SQL Pivot查询在每列

时间:2017-06-09 11:36:38

标签: sql sql-server dynamic pivot

我在使用我创建的数据透视表创建查询时需要一些帮助,但我遇到的问题是,当我在任何列查询上应用聚合函数时,会为每列添加该值。

create table #skillsTemp
(
    RowNumber INT IDENTITY(1, 1),
    ResourceId INT,
    Caption VARCHAR(MAX),
    SubPracticeName VARCHAR(1000),
    SkillName VARCHAR(MAX),
    IsActive BIT,
    IsCoreSkill INT,
    TrainingTypeId INT
)


INSERT INTO #skillsTemp (ResourceId, Caption, SubPracticeName, SkillName, IsActive, IsCoreSkill, TrainingTypeId)

SELECT Resource.ResourceId, Resource.Caption, SubPracticeName, SkillName, IsActive, MAX(IsCoreSkill) IsCoreSkill,  ResourceAttribute.TrainingTypeId FROM Resource INNER JOIN
SubPractice ON SubPractice.SubPracticeId = Resource.SubPracticeId LEFT OUTER JOIN
SkillMaster ON SkillMaster.SubPracticeId = SubPractice.SubPracticeId LEFT OUTER JOIN
ResourceAttribute ON ResourceAttribute.ResourceId = Resource.ResourceId 

WHERE ResourceTypeId = 6 AND Resource.IsDeleted = 0 AND SkillMaster.SubPracticeId = 1
GROUP BY Resource.ResourceId, Resource.Caption, SkillName, SubPracticeName, ResourceAttribute.TrainingTypeId, IsActive


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

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.SkillName)
            FROM #skillsTemp c
            where IsCoreSkill = 1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
SET @secondaryCols = STUFF((SELECT distinct ',' + QUOTENAME(c.SkillName)
    FROM #skillsTemp c
    WHERE IsCoreSkill = 0
    FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)') 
,1,1,'')

set @query = 'SELECT  Caption, ''A'' AS Priority, ' + @cols + ', ' + @secondaryCols + '  from 
            (
                select ResourceId
                    , Caption
                    , SkillName,
                    IsActive
                from #skillsTemp
           ) x
            pivot 
            (
                MAX(ResourceId) 
                for SkillName in (' + @cols + ', ' + @secondaryCols + ')
            ) p'

SELECT @query

执行(@query)

这是我的整个查询。它返回2条记录,但它在每列填充ReourceId作为值。我需要的是如果Fico有一些那么它应该显示给Fico而不是显示给所有列。

  

标题,优先级,FICO,现金管理是列,而X和Y是不同的值。

实际输出:

标题优先FICO现金管理。 Shreesh测试A 28983 28983
测试测试A 28966 28966

预期产出: 标题优先FICO现金管理。 Shreesh测试A X 0
测试测试A 0 Y

0 个答案:

没有答案