Mastering SQL Server Row-to-column and column-changing careers
1. List of career change
After the data is processed, the data source of the front-end chart will be generated directly, but the data must be written into the intermediate table by the program, and the data can be queried directly from the intermediate table the next time the data is queried.
1.1 Column Line Wrapping syntax
Table_sourceunpivot (value_columnfor pivot_columnin (<column_list>))
1.2 Row to column case
With TAS ( Select 1 as Teamid, ' Test team 1 ' as team,80 ' men ', ' women ' UNION SELECT 2 as Teamid, ' Test Team 2 ' as team,30 ' Men ', women ')---career------------------------------------SELECT teamid,team, Type=attribute,cnt=valuefrom T UNPIVOT ( VALUE for ATTRIBUTE in ([Men],[women])) as UPV
2, Row to column
Row-to-column data is primarily queried from the middle table, and the following versions of SQL SERVER2005 can be done using aggregate functions.
2.1 Row to column syntax
Table_sourcepivot (Aggregation function (value_column) for Pivot_columnin (<column_list>))
2.2, using pivot to achieve
With TAS ( select 1 as ID, ' Test team 1 ' team, ' Men ' item,80 CENT UNION SELECT 1 as ID, ' Test team 1 ' team, ' women ' item,20 CENT Union Select 2 as ID, ' Test Team 2 ' team, ' Men ' item,30 CENT Union Select 2 as ID, ' Test Teams 2 ' team, ' women ' item,70 CENT) SELECT * from-T PIVOT (SUM (CENT) for ITEM in ([Men],[women])) A
2.3, using the aggregation function to implement
With TAS ( select 1 as ID, ' Test team 1 ' team, ' Men ' item,80 CENT UNION SELECT 1 as ID, ' Test team 1 ' team, ' women ' item,20 CENT Union Select 2 as ID, ' Test Team 2 ' team, ' Men ' item,30 CENT UNION Select 2 as ID, ' Test team 2 ' TEAM, ' women ' item,70 CENT) SELECT id,team,sum (case when item= "men" then CENT ELSE 0 END) "Men", SUM (case when item= ' women ') Then CENT ELSE 0 END) ' Women ' from Tgroup by Id,team
Resources
Http://www.cnblogs.com/zhangzt/archive/2010/07/29/1787825.html
Http://www.cnblogs.com/aspnethot/articles/1762665.html
SQL Server handles row-to-column and column-changing careers