sql-Row to Column

Source: Internet
Author: User

sql-Row to Column

DECLARE @sql_str NVARCHAR (MAX)

DECLARE @sql_col NVARCHAR (MAX)

DECLARE @tableName SYSNAME--line-to-go list

DECLARE @groupColumn SYSNAME--Group field

DECLARE @row2column SYSNAME--Row Variable column field

DECLARE @row2columnValue SYSNAME--field for row variable column values

SET @tableName = ' temp '

SET @groupColumn = ' T_userid '

SET @row2column = ' T_protitname '

SET @row2columnValue = ' T_infoanswer '

--get columns that may exist from the row data

SET @sql_str = N '

SELECT @sql_col_out = ISNULL (@sql_col_out + "," "," ") + QUOTENAME ([' [email protected]+ '])

from [' [E-mail protected]+ '] GROUP by [' [email protected]+ '] '

--print @sql_str

EXEC sp_executesql @sql_str, N ' @sql_col_out NVARCHAR (MAX) output ', @[email protected]_col output

--print @sql_col

SET @sql_str = N '

SELECT * FROM (

SELECT [' [Email protected]+ '],[' [email protected]+ '],[' [email protected]+ '] from [' [email protected]+ '] ' p PIVOT

(MAX ([' [email protected]+ ']) for [' [E-mail protected]+ '] in (' + @sql_col + ')) As Pvt

ORDER by Pvt. [' [Email protected]+ '] '

--print (@sql_str)

EXEC (@sql_str)

sql-row to column

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.