SQL行列轉換的簡單方法
在SQL中,轉換行列資料以獲得更實用的資料格式是常見的需求。雖然PIVOT函數看起來複雜,但其實還有更簡單的替代方法。
使用UNION ALL、聚合函數和CASE語句
如果無法使用PIVOT函數,可以使用UNION ALL、聚合函數和CASE語句的組合:
<code class="language-sql">select name, sum(case when color = 'Red' then value else 0 end) Red, sum(case when color = 'Green' then value else 0 end) Green, sum(case when color = 'Blue' then value else 0 end) Blue from ( select color, Paul value, 'Paul' name from yourTable union all select color, John value, 'John' name from yourTable union all select color, Tim value, 'Tim' name from yourTable union all select color, Eric value, 'Eric' name from yourTable ) src group by name</code>
靜態UNPIVOT和PIVOT方法
如果需要轉換的欄位值已知,可以使用UNPIVOT和PIVOT函數:
<code class="language-sql">select name, [Red], [Green], [Blue] from ( select color, name, value from yourtable unpivot ( value for name in (Paul, John, Tim, Eric) ) unpiv ) src pivot ( sum(value) for color in ([Red], [Green], [Blue]) ) piv</code>
動態PIVOT方法
對於未知數量的欄位和顏色,可以使用動態SQL:
<code class="language-sql">DECLARE @colsUnpivot AS NVARCHAR(MAX), @query AS NVARCHAR(MAX), @colsPivot as NVARCHAR(MAX) select @colsUnpivot = stuff((select ','+quotename(C.name) from sys.columns as C where C.object_id = object_id('yourtable') and C.name <> 'color' for xml path('')), 1, 1, '') select @colsPivot = STUFF((SELECT ',' + quotename(color) from yourtable t FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'select name, '+@colsPivot+' from ( select color, name, value from yourtable unpivot ( value for name in ('+@colsUnpivot+') ) unpiv ) src pivot ( sum(value) for color in ('+@colsPivot+') ) piv' exec(@query)</code>
以上是如何在 SQL 中輕鬆轉置列和行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!