2012-05-29 143 views
7

我寫了這個查詢的不同值的不確定量:樞軸與

SELECT s, [1] AS a1, [2] AS a2, [3] AS a3, [4] AS a4 
FROM (SELECT grade, aid, s FROM m) p 
PIVOT 
(
SUM(grade) 
FOR aid IN ([1], [2], [3], [4]) 
) AS pvt ORDER BY pvt.s; 

返回結果:

s a1 a2 a3 a4 
1 25 69 95 56 
2 27 99 16 87 
. . . . 
99 98 12 34 76 

這正是我想要的結果。我的問題是,'援助'中不會總是有四個不同的值。是否有可能重寫此查詢(或使用存儲過程),以便'a *'列的數量取決於'aid'中有多少個不同的值?

回答

11

您將需要使用Dynamic Pivot來獲取所需列的列表。這將首先檢索列的列表,然後旋轉該列表。一些與此類似:

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(aid) 
      FROM m 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT s, ' + @cols + ' from 
      (
       select grade, aid, s 
       from m 
      ) x 
      pivot 
      (
       sum(grade) 
       for aid in (' + @cols + ') 
      ) p 
      ORDER BY p.s' 

execute(@query) 
+0

哇謝謝,這正是我想要的! –

+1

+1 - 雖然很挑剔,但您錯過了列的別名 – Lamak

2

Lamak:這裏是我如何與列別名做到了。別名鏈接到另一個表中通過`aid'鏈接的列中的值。

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

SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(aid) 
    FROM m 
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

SELECT @colsAlias = STUFF((SELECT DISTINCT ',' + QUOTENAME(m.aid) + ' AS ' + QUOTENAME(n.aName) 
    FROM m INNER JOIN n ON m.aid = n.aid 
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

SET @query = 'SELECT s, ' + @colsAlias + ' FROM 
       (
       SELECT grade, aid, s 
        FROM m 
       ) x 

      PIVOT 
      (
       MIN(grade) FOR aid IN (' + @cols + ') 
      ) p ' 

EXECUTE(@query)