How to convert rows into columns in SQL queries

Source: Internet
Author: User
The table has three columns: stunamem and subjectscore. table data includes: zhang San Language 0 Li Si Language 4 Wang Er English 90 Zhang San mathematics 333 requirements query results below student language English mathematics Zhang San 00333 Li Si 400 No score is 0 by default query SQL downstairs. use casewhenSQLcode * Title: normal

The table has three columns: stunamem and subject score. table data includes: zhang San Language 0 Li Si Language 4 Wang Er English 90 Zhang San mathematics 333 requirements query results: students language English mathematics Zhang San 0 0 0 333 Li Si 4 0 0 No score default 0 search query SQL and other downstairs. use case when SQL code/* Title: normal

The table has three columns: stunamem and subject score.
Table data includes:
Zhang San Language 0
Li Si Language 4
Wang 'er English 90
Zhang San, mathematics 333
RequirementsQueryThe result is as follows:
Chinese and English mathematics for students
Zhang San 0 0 333
Li Si 4 0 0
The default value of no score is 0.


PleaseQuerySQL

Wait downstairs.

Use case when

SQL code

/*

Title: normal row/column conversion (version 2.0)

Author: AI xinjue Luo. Xin Hua)

Time: 2008-03-09

Location: Shenzhen, Guangdong Province

Note: normal row/column conversion (version 1.0) only provides static and dynamic writing for SQL server 2000, and version 2.0 adds SQL server 2005 related writing.



Question: Suppose there is a student orders table (tb) as follows:

Name course score

Zhang San Language 74

James math 83

Zhang San physical 93

Li Si language 74

Li Si mathematics 84

Li Si physical 94

ThinkChange(The following result is displayed ):

Name, Chinese, Mathematics, Physics

----------------

Li Si 74 84 94

Zhang San 74 83 93

-------------------

*/



Create table tb (name varchar (10), course varchar (10), score int)

Insert into tb values ('zhang san', 'China', 74)

Insert into tb values ('zhang san', 'mat', 83)

Insert into tb values ('zhang san', 'Physical ', 93)

Insert into tb values ('Li si', 'China', 74)

Insert into tb values ('Li si', 'mat', 84)

Insert into tb values ('lily', 'Physical ', 94)

Go



-- SQL server 2000 static SQL indicates that the course only includes three courses: Chinese, mathematics, and physics. (Same as below)

Select name as name,

Max (case course when 'China' then score else 0 end) language,

Max (case course when 'mate' then score else 0 end) math,

Max (case course when 'physical 'then score else 0 end) Physical

From tb

Group by name



-- SQL server 2000 dynamic SQL refers to three courses, including Chinese, mathematics, and physics. (Same as below)

Declare @ SQL varchar (8000)

Set @ SQL = 'select name'

Select @ SQL = @ SQL + ', max (case course when''' + course + ''' then score else 0 end) [' + course + ']'

From (select distinct course from tb) as

Set @ SQL = @ SQL + 'from tb group by name'

Exec (@ SQL)



-- SQL server 2005 static SQL.

Select * from (select * from tb) a between (max (score) for course in (Chinese, Mathematics, Physics) B



-- SQL server 2005 dynamic SQL.

Declare @ SQL varchar (8000)

Select @ SQL = isnull (@ SQL + '], [', '') + course from tb group by course

Set @ SQL = '[' + @ SQL + ']'

Exec ('select * from (select * from tb) a round (max (score) for course in ('+ @ SQL +') B ')



---------------------------------



/*

Problem: Based on the above results, the average score and total score are added. The following result is obtained:

Name, Chinese, mathematics, and physics average score

--------------------------

Li Si 74 84 94 84.00 252

Zhang San 74 83 93 83.33 250

*/



-- SQL server 2000 static SQL.

Select name,

Max (case course when 'China' then score else 0 end) language,

Max (case course when 'mate' then score else 0 end) math,

Max (case course when 'physical 'then score else 0 end) physics,

Cast (avg (score * 1.0) as decimal () average score,

Sum (score) total score

From tb

Group by name



-- SQL server 2000 dynamic SQL.

Declare @ SQL varchar (8000)

Set @ SQL = 'select name'

Select @ SQL = @ SQL + ', max (case course when''' + course + ''' then score else 0 end) [' + course + ']'

From (select distinct course from tb) as

Set @ SQL = @ SQL + ', average score of cast (avg (score * 1.0) as decimal (), total sum (score) from tb group by name'

Exec (@ SQL)



-- SQL server 2005 static SQL.

Select m. *, n. Average score, n. Total score from

(Select * from tb) a between (max (score) for course in (Chinese, Mathematics, Physics) B) m,

(Select name, cast (avg (score * 1.0) as decimal () average score, sum (score) total score from tb group by name) n

Where m. Name = n. Name



-- SQL server 2005 dynamic SQL.

Declare @ SQL varchar (8000)

Select @ SQL = isnull (@ SQL + ',', '') + course from tb group by course

Exec ('select m. *, n. Average score, n. Total score from

(Select * from tb) a round (max (score) for course in ('+ @ SQL +') B) m,

(Select name, cast (avg (score * 1.0) as decimal () average score, sum (score) total score from tb group by name) n

Where m. Name = n. name ')



Drop table tb



------------------

------------------



/*

Question: If the two tables change each other: the table structure and data are:

Name, Chinese, Mathematics, Physics

Zhang San 74 83 93

Li Si 74 84 94

ThinkChange(The following result is displayed ):

Name course score

------------

Li Si language 74

Li Si mathematics 84

Li Si physical 94

Zhang San Language 74

James math 83

Zhang San physical 93

--------------

*/



Create table tb (name varchar (10), Chinese int, mathematical int, physical int)

Insert into tb values ('zhang san', 93)

Insert into tb values ('Lee 4', 94)

Go



-- SQL server 2000 static SQL.

Select * from

(

Select name, course = 'China', score = Chinese from tb

Union all

Select name, course = 'mat', score = mathematics from tb

Union all

Select name, course = 'physical ', score = physical from tb

) T

Order by name, case course when 'China' then 1 when' math 'then 2 when' then 3 end



-- SQL server 2000 dynamic SQL.

-- Call the dynamic ecosystem of the system table.

Declare @ SQL varchar (8000)

Select @ SQL = isnull (@ SQL + 'Union all', '') + 'select Name, [course] = '+ quotename (Name, ''') + ', [score] = '+ quotename (Name) + 'from tb'

From syscolumns

Where name! = N'name' and ID = object_id ('tb') -- table name tb, excluding other columns whose names are names

Order by colid asc

Exec (@ SQL + 'order by name ')



-- SQL server 2005 dynamic SQL.

Select name, course, score from tb unaligned (score for course in ([language], [mathematics], [physics]) t



-- SQL server 2005 dynamic SQL, same as SQL server 2000 dynamic SQL.



--------------------

/*

Problem: add an average score and the total score to the above result. The following result is obtained:

Name course score

----------------

Li Si language 74.00

Li Si, mathematics 84.00

Li Si physical 94.00

Li Si average score 84.00

Li Si's total score is 252.00

Zhang San Chinese 74.00

Zhang San, mathematics 83.00

Zhang San physical 93.00

Michael Jacob has an average score of 83.33.

Zhang San's total score is 250.00

------------------

*/



Select * from

(

Select name as name, course = 'China', score = Chinese from tb

Union all

Select name as name, course = 'mat', score = mathematics from tb

Union all

Select name as name, course = 'physical ', score = physical from tb

Union all

Select name as name, course = 'average', score = cast (Chinese + mathematics + physics) * 1.0/3 as decimal () from tb

Union all

Select name as name, course = 'Total', score = Chinese + mathematics + physics from tb

) T

Order by name, case course when 'China' then 1 when' math 'then 2 when' 'then 3 when' average score 'then 4 when' total score 'then 5 end



Drop table tb



SQL code

Create table # test (stunamem varchar (10), subject varchar (10), score int)

Insert # test select 'zhang san', 'China', 0

Insert # test select 'Li si', 'China', 4

Insert # test select 'wang 2', 'English ', 90

Insert # test select 'zhang san', 'mat', 333







Select stunamem, max (case when subject = 'China' then score else 0 end)

, Max (case when subject = 'English 'then score else 0 end)

, Max (case when subject = 'mate' then score else 0 end)

From # test

Group by stunamem

Stunamem

-------------------------------------------

Li Si 4 0 0

Wang er0 90 0

Zhang San 0 0 333



(3 rows affected)



If it is 2005, you can use the functions.
SQL code



, [1996], [1997], [1998]

FROM dbo. Orders

Partition (

SUM (Quantity)

FOR [Year] IN ([1996], [1997], [1998])

) X

-- Result:

Custom ID 1996 1997 1998

-------------------------------------------

ANTON 24 295 40

BONAP 181 486 313

BOTTM 81, 454, 421






For more information, see use of the SQL server 2005 limit operator.

[Code = SQL]
USE tempdb
GO
Select year (OrderDate) AS [Year]
, CustomerID
, Od. Quantity
INTO dbo. Orders
FROM NorthWind... Orders AS o
JOIN NorthWind... [Order Details] AS od
ON o. OrderID = od. OrderID
WHERE o. CustomerID IN ('bonap ', 'bottm', 'anton ')

SELECT CustomerID
, [1996], [1997], [1998]
FROM dbo. Orders
Partition (
SUM (Quantity)
FOR [Year] IN ([1996], [1997], [1998])
) X

-- Result:
Custom ID 1996 1997 1998
-------------------------------------------
ANTON 24 295 40
BONAP 181 486 313
BOTTM 81, 454, 421


[/Code]

Blog: http://www.cnblogs.com/www56/archive/2010/11/06/1870576.html

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.