SQL Server 中的數據透視表提供了一種強大的方法,可以將數據從行轉置為列。但是,用戶在構建正確的查詢時可能會遇到挑戰。
針對已知列值使用 PIVOT 函數:
對於預定義的列值(在本例中為周數),可以直接使用 PIVOT 函數:
<code class="language-sql">select * from ( select store, week, xCount from yt ) src pivot ( sum(xcount) for week in ([1], [2], [3]) ) piv;</code>
動態生成透視列值:
為了處理未知的列值(例如動態的周數),可以使用動態 SQL 和窗口函數的組合:
<code class="language-sql">DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT ',' + QUOTENAME(Week) from yt group by Week order by Week FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT store,' + @cols + ' from ( select store, week, xCount from yt ) x pivot ( sum(xCount) for week in (' + @cols + ') ) p ' execute(@query);</code>
結果:
兩種方法都產生相同的結果:
| 101 | 138 | 282 | 220 |
| 102 | 96 | 212 | 123 |
| 105 | 37 | 78 | 60 |
| 109 | 59 | 97 | 87 |
以上是如何使用樞軸函數將行轉換為SQL Server中的列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!