如何动态使用数据透视查询

时间:2014-06-18 02:56:05

标签: sql sql-server pivot

我在这里有一个查询:(这是修改过的。谢谢你的帮助)我正在使用mssql 2008

SELECT 'Risk','ADAB','Bahrain','Kuwait','Masirah','Qatar' <-- fixed
UNION ALL
select CONVERT(VARCHAR,risk)
,CONVERT(VARCHAR,[ADAB]) as ADAB <-- fixed
,CONVERT(VARCHAR,[Bahrain]) as Bahrain <-- fixed
,CONVERT(VARCHAR,[Kuwait]) as Kuwait <-- fixed
,CONVERT(VARCHAR,[Masirah]) as Masirah <-- fixed
,CONVERT(VARCHAR,[Qatar]) as Qatar <-- fixed

from (select risk, piv_site = risk, site
        from qcvqciffull
        where (1=1) AND Risk is not null) as ps
pivot (count(piv_site)
        for site in ([ADAB], [Bahrain], [Kuwait], [Masirah], [Qatar])) as pvt <-- fixed

我这里有一个fiddle。是否可以将那些在其旁边有“固定”文本的字段转为动态转动?比如,我有一条新记录,例如USA。有办法吗?

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

对于当前的场景,您必须添加除此之外的任何文本。

您可以使用动态数据透视表自动查找和创建列,您必须在其中创建动态查询然后执行。

请参阅: - Dynamic Pivot

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
       + QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses

--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
  N'SELECT Year, ' + @ColumnName + '
    FROM #Tablename
    PIVOT(SUM(Earning)
          FOR Course IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery