sql strong line transfer column function (built-in function pivot and precautions)

grammar:

PIVOT for rotating the column value for a column name (i.e., column lines switch), the SQL Server 2000 can be implemented with the CASE statement with aggregate function

PIVOT general syntax is: PIVOT (aggregate function (column) Column the FOR in (...)) AS P

The complete syntax:

table_source

PIVOT(

Aggregate functions (value_column in)

FOR pivot_column

IN(<column_list>)

)

UNPIVOT used to set out into column values ​​(that is, the column switch) in SQL Server 2000 can be used to achieve UNION

The complete syntax:

table_source

UNPIVOT(

value_column

FOR pivot_column

IN(<column_list>)

)

Note: PIVOT, UNPIVOT is SQL Server 2005 syntax, and is required to modify the database compatibility level of
 the database Properties -> Options -> changed to compatibility level 90

 

IF  object_id ( ' TB ' ) IS  Not  null  drop  Table TB
 Go 
Create  Table TB (name VARCHAR ( 10 ), the course VARCHAR ( 10 ), the score int )
 INSERT  INTO TB values ( ' John Doe ' , ' language ' , 74 )
 INSERT  INTO TB values ( ' Joe Smith ' , ' Mathematics' , 83 )
 INSERT  INTO TB values ( ' John Doe ' , ' physical ' , 93 )
 INSERT  INTO TB values ( ' John Doe ' , ' language ' , 74 )
 INSERT  INTO TB values ( ' John Doe ' , ' mathematics ' , 84 )
 INSERT  INTO TB values ( 'John Doe ' , ' physical ' , 94 )
 Go 

SELECT  *  from TB

 

 

method one:

The question now is: I want this person three statistical results by name, namely: the name of the language of mathematical physics

First look at using time case when end structure:

 

select name,
  max ( Case course the when  ' language '  the then score the else  0  End ) language,
  max ( Case course the when  ' mathematical ' the then score the else  0  End ) mathematics,
  max ( Case course the when  ' physical ' the then score the else  0  End ) Physics
 from TB
 Group  by name

Option two: pivot function

the SELECT  *  from TB Pivot ( max (score) for courses in (language, mathematics, physics)) a

Provided that the above query:

PIVOT, UNPIVOT is SQL Server 2005 syntax, and is required to modify the database compatibility level of
 the database Properties -> Options -> changed to compatibility level 90

If you do not change the compatibility level 90, the query results are as follows:

Guess you like

Origin www.cnblogs.com/zoro-zero/p/11334785.html