-
First we set up a table, named Rtoc, each field of the design such as, respectively, is Name,course,score, representing the name, scores and scores,.
- 2
We added data to the table to add Xiao Ming and floret of the language and math scores.
- 3
Next, we're going to do a row-and-column conversion, which should be name, language, math. We first have to consider how to get the column names, we can get the course name by grouping. , we can see the stitching string of the course name from the query result through the grouping statement.
Code:
Declare @sql varchar ($) Select @sql = ISNULL (@sql+',',') + from Group by Course Select @sql
Effect:
- 4
Next, the key row-to-column function pivot comes out, through which we populate the fractions into the converted column-language, mathematical column values.
Declare @sql varchar( $)Select @sql=ISNULL(@sql+',',"')+Course fromRtocGroup byCourseSet @sql='SELECT * from Rtoc pivot (max (score) for course in ('+@sql+')) T' exec(@sql)
- 5
After we run, we can get the result of the row-to-column, as shown in.
- 6
Through the above steps, we can easily achieve the transformation of the ranks. Similarly, what should we do if we want to convert the columns into rows? We can also use the Unpivot function as an easy implementation.
SQL row and column conversions