用于多列的动态SQL的数据透视表

时间:2016-01-13 21:25:22

标签: sql-server tsql

SQL Pivot和动态SQL新手。我有一个带有列的表,我想使不同的属性成为数据透视表中的列标题,同时还为关于主数据的其他列创建正确的主要类别,并在这些字段中报告分数。问题是我无法正确填充分数或不同的列标题。

我无法将Measure1字段变为列标题,我无法获得分数。使用与Measure1和相关分数相关的正确[度量名称]。感谢您提前提供任何帮助。

Declare @ColumnNames NVARCHAR (MAX) = ''
Declare @SQL NVARCHAR (MAX)= ''

Select @ColumnNames += QUOTENAME([Measure1]) + ','
From [dbo].[Table1]

Group By [Measure1]

SET @ColumnNames = LEFT(@ColumnNames, LEN(@ColumnNames)-1)
SET @SQL =
'Select * FROM
(Select
    case
        When [measure1] like ''%lower%'' then ''Lower''
        When [measure1] like ''%upper%'' then ''Upper''
        When [measure1] like ''%Days%'' then ''Days''
        When [measure1] like ''%Occur%'' then ''Occurrences''
        When [measure1] like ''%Pred%'' then ''Predicted''
        When [measure1] like ''%Ratio%'' then ''Ratio''
        end as [Measure1]
    ,case
        When [Measure Name] like ''%Tewksbury%'' then ''Stan''
        When [Measure Name] like ''%Boston%'' then ''Steve''
        When [Measure Name] like ''%Seattle%'' then ''Payton''
        When [Measure Name] like ''%Denver%'' then ''Lavell''
        When [Measure Name] like ''%Houston%'' then ''Caren''
        When [Measure Name] like ''%Hudson%'' then ''Michael''
        end as Measure_Category
    ,[Main ID] AS [Cust ID]
    ,[Compared to Average]
    ,[score]

From
    [dbo].[Table1]
) AS BaseData

PIVOT (
    MAX([Compared to Average])
    FOR [measure1]
    IN (' + @ColumnNames + 

')) AS PivotTable'



Execute sp_executesql @SQL

实际结果: enter image description here

期望的结果: enter image description here

关闭所需结果: enter image description here

1 个答案:

答案 0 :(得分:1)

您的getPreferredSize参数与您在透视查询中实际选择的内容不匹配,因此您可能希望将JFrame#pack参数更改为此类内容。< / p>

@ColumnNames

你可以不用这个。

@ColumnNames