SQL Server row to column

Source: Internet
Author: User

First Kind

SELECT title,
SUM (Case typeid if ' 1 ' then gjdate ELSE 0 END) as ' take some ',
SUM (case typeid if ' 2 ' then gjdate ELSE 0 END) as ' leave ',
SUM (Case typeid if ' 3 ' then gjdate ELSE 0 END) as ' overtime '
From LFIL_TB
GROUP by Title


The second Kind



DECLARE @sql_str NVARCHAR (max) DECLARE @sql_col NVARCHAR (max) DECLARE @tableName SYSNAME--table name declare @groupColumn SYSNAME--Group Field (title name what thing) DECLARE @row2column SYSNAME--row-to-column fields declare @row2columnValue SYSNAME--field set @tableName for row variable column values='LFIL_TB'SET @groupColumn='title'SET @row2column='typeID'SET @row2columnValue='gjdate'--gets the column set that may exist from the row data @sql_str= N'SELECT @sql_col_out = ISNULL (@sql_col_out +"',"'," '") + QUOTENAME (['[Email protected]+']) from ['[Email protected]+'] GROUP by ['[Email protected]+']'--PRINT @sql_strEXEC sp_executesql @sql_str, N'@sql_col_out NVARCHAR (MAX) OUTPUT', @sql_col_out =@sql_col OUTPUT--PRINT @sql_colSET @sql_str= N'SELECT *From (SELECT ['[Email protected]+'],['[Email protected]+'],['[Email protected]+'] FROM ['[Email protected]+']) P PIVOT (SUM (['[Email protected]+']) for ['[Email protected]+'] In ('+ @sql_col +') as Pvt ORDER by Pvt. ['[Email protected]+']'--PRINT (@sql_str) EXEC (@sql_str)





SQL Server row to column

Related Article

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.