SQL 列和行转置:实用指南
SQL 通常需要转置数据 - 将表方向从垂直(列)转换为水平(行)或相反。虽然存在 PIVOT
命令,但它可能很麻烦。 本指南探讨了更简单的替代方案。
方法 1:UNION ALL、聚合和 CASE 语句
此方法使用 UNION ALL
进行逆透视,然后使用聚合函数(此处为 SUM
)和 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>
方法2:静态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>
方法3:变量列的动态透视
在处理动态数量的列和颜色时,动态 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 中进行数据转置的通用方法,适应各种数据操作需求。
以上是如何在SQL中高效地转置列和行?的详细内容。更多信息请关注PHP中文网其他相关文章!