Home > Database > Mysql Tutorial > How to Efficiently Transpose Rows into Columns in SQL Server?

How to Efficiently Transpose Rows into Columns in SQL Server?

Barbara Streisand
Release: 2025-01-25 14:58:11
Original
332 people have browsed it

How to Efficiently Transpose Rows into Columns in SQL Server?

In the SQL Server, the row is efficiently converted into a column

SQL Server provides a variety of methods to convert data from rows to columns.

Pivot function

PIVOT function allows the use of the following syntax to directly transform data:

<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>
Copy after login
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>
Copy after login
The polymerization function and case expression

or, you can use the polymer function:

<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>
Copy after login
multiple connections

In the case of a closed column, you can use 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template