2016-09-27 41 views
0

我有以下如何使動態SQL支點

select country,city,school,class,quantity from tableA 

我想樞軸SELECT語句是基於類像見下表:

country City School ClassA ClassB ClassC ClassD 
XXX AAA SCH01 37 37 39 37 
XXX BBB SCH02 12 12 1 12 
XXX BBB SCH03 6 6 9 6 
XXX DDD SCH04 1 1 1 1 
YYY ABC SCH05 1 1 1 1 
YYY CDE SCH06 1 1 1 1 
YYY EDY SCH07 1 1 1 1 
YYY ZER SCH08 1 1 1 1 
SSS GFY SCH09 1 1 1 1 
SSS AHY SCH10 1 1 1 1 
+1

標記您正在使用的dbms。 (答案可能是產品特定的。) – jarlh

回答

0

MS SQL服務器:

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

select @cols = STUFF((SELECT ',' + QUOTENAME([class]) 
        from [table-name] 
        group by [class] 
        order by [class] 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT [country], [city], [school],' + @cols + ' from 
      (
       select [country], [city], [school],[class],[quantity] 
       from [table-name] 
      ) x 
      pivot 
      (
       sum([quantity]) 
       for [class] in (' + @cols + ') 
      ) p ' 

execute(@query);