Home >Database >Mysql Tutorial >How to Efficiently Transpose Rows into Columns in SQL Server?
In the SQL Server, the row is efficiently converted into a column
Pivot function
<code class="language-sql">select Firstname, Amount, PostalCode, LastName, AccountNumber from ( select value, columnname from yourtable ) d pivot ( max(value) for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber) ) piv;</code>For the unknown situation of the number of columns, you can use the dynamic SQL:
<code class="language-sql">DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) from yourtable group by ColumnName, id order by id FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = N'SELECT ' + @cols + N' from ( select value, ColumnName from yourtable ) x pivot ( max(value) for ColumnName in (' + @cols + N') ) p ' exec sp_executesql @query;</code>The polymerization function and case expression
<code class="language-sql">select max(case when columnname = 'FirstName' then value end) Firstname, max(case when columnname = 'Amount' then value end) Amount, max(case when columnname = 'PostalCode' then value end) PostalCode, max(case when columnname = 'LastName' then value end) LastName, max(case when columnname = 'AccountNumber' then value end) AccountNumber from yourtable</code>multiple connections
The above is the detailed content of How to Efficiently Transpose Rows into Columns in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!