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 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
(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
(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
--------------------------------------------------
Below is the dawugui reply
--------------------------------------------------
Create Table A (ID char (3), num1 int, num2 int, num3 int, num4 INT)
Insert a select '001', 80, 90, 50, 60
Insert a select '002 ', 84, 70, 60, 82
Go
-- Sql2005 implementation method:
Select * from
Unregister
(Num for col in ([num1], [num2], [num3], [num4]) T2) TMP
-- SQL2000 implementation:
--- Call the dynamic ecosystem of system tables
Declare @ s nvarchar (4000)
Select @ s = isnull (@ s + 'Union all', '') + 'select ID, [num] = '+ quotename (name, ''') + ', qty = '+ quotename (name) +' from'
From syscolumns
Where name! = N'id' and ID = object_id ('A') -- table name a, excluding other columns whose column name is ID
Order by colid ASC
Exec (@ s + 'order by id asc, [num] ASC ')
-- Generated static statement
Select ID, [num] = 'num1', qty = [num1] from a union all
Select ID, [num] = 'num2', qty = [num2] from a union all
Select ID, [num] = 'num3', qty = [num3] from a union all
Select ID, [num] = 'num4', qty = [num4] from
Order by id asc, [num] ASC
/*
Id num Qty
-------------------
001 num1 80
001 num2 90
001 num3 50
001 num4 60
002 num1 84
002 num2 70
002 num3 60
002 num4 82
------------------------------
*/
-- Dynamic method:
Declare @ s nvarchar (4000)
Select @ s = isnull (@ s + 'Union all', '') + 'select ID, [num] = '+ quotename (name) + 'from'
From syscolumns
Where name! = N'id' and ID = object_id ('A ')
Order by colid ASC
Exec (@ s + 'order by id asc ')
-- The generated statement is as follows:
Select ID, [num] = [num1] from a union all
Select ID, [num] = [num2] from a union all
Select ID, [num] = [num3] from a union all
Select ID, [num] = [num4] from
Order by id asc, [num] ASC
/*
Id num
---------------
001 80
001 90
001 50
001 60
002 82
002 60
002 70
002 84
*/
--- Drop Table
/*
Rotate table data 90 degrees (in Sanya, Hainan)
Run the following table:
A B C D E
----------------------------------------------------------------
X 1 2 3 4
Y 5 6 7 8
Z 9 10 11 12
Convert to the following result:
A X Y Z
--------------------------------------------------
B 1 5 9
C 2 6 10
D 3 7 11
E 4 8 12
*/
-- Generate Test Data
Create Table test1 (A varchar (20), B INT, C int, d int, e INT)
Insert into test1 select 'x', 1, 2, 3, 4
Insert into test1 select 'y', 5, 6, 7, 8
Insert into test1 select 'Z', 9, 10, 11, 12
Go
-- Generate an intermediate data table
Declare @ s varchar (8000)
Set @ s = 'create table Test2 (A varchar (20 )'
Select @ s = @ s + ',' + A + 'varchar (10)' from test1
Set @ s = @ s + ')'
Exec (@ s)
Print @ s
-- Use an intermediate table to convert rows and columns
Declare @ name varchar (20)
Declare t_cursor cursor
Select name from syscolumns
Where id = object_id ('test1') and colid> 1 order by colid
Open t_cursor
Fetch next from t_cursor into @ name
While @ fetch_status = 0
Begin
Exec ('select' + @ name + 'as t into test3 from test1 ')
Set @ s = 'insert into Test2 select ''' + @ name + ''''
Select @ s = @ s + ', ''' + rtrim (t) + ''' from test3
Exec (@ s)
Exec ('drop table test3 ')
Fetch next from t_cursor into @ name
End
Close t_cursor
Deallocate t_cursor
-- View the result of row/column swaps
Select * From test1
Select * From Test2
-- Delete a table
Drop table test1
Drop table Test2
----------------------------------------------------------------------------
/* Fixed statement :*/
Select T1. *, t2.y, t3.z from
(Select a = 'B', x = B from test1 where a = 'X') T1,
(Select a = 'B', y = B from test1 where a = 'y') T2,
(Select a = 'B', Z = B from test1 where a = 'Z') T3
Where t1.a = t2.a and t1.a = t2.a
Union all
Select T1. *, t2.y, t3.z from
(Select a = 'C', x = C from test1 where a = 'X') T1,
(Select a = 'C', y = C from test1 where a = 'y') T2,
(Select a = 'C', Z = C from test1 where a = 'Z') T3
Where t1.a = t2.a and t1.a = t2.a
Union all
Select T1. *, t2.y, t3.z from
(Select a = 'D', x = D from test1 where a = 'X') T1,
(Select a = 'D', y = D from test1 where a = 'y') T2,
(Select a = 'D', Z = D from test1 where a = 'Z') T3
Where t1.a = t2.a and t1.a = t2.a
Union all
Select T1. *, t2.y, t3.z from
(Select a = 'E', x = E from test1 where a = 'X') T1,
(Select a = 'E', y = E from test1 where a = 'y') T2,
(Select a = 'E', Z = E from test1 where a = 'Z') T3
Where t1.a = t2.a and t1.a = t2.a
----------------------------------------------------------------------------
/*
Table TB with the following data:
Project type Performance Improvement
Blow cleaning class 200 10
Takeout 100 5
Total 300 15
Convert:
Total project categories
Performance: 200, 100, 300
Commission 10 5 15
*/
Create Table TB
(
Project type varchar (10 ),
Performance int,
Commission int
)
Insert into Tb (project type, performance, Commission) values ('Blow-playing class)
Insert into Tb (project type, performance, Commission) values ('takeout ', 5)
Insert into Tb (project type, performance, Commission) values ('Total', 15)
Go
Select project type, sum (blow) as blow, sum (take-out) as take-out, sum (total) as total from
(
Select project type = 'performance ',
Blow-cleaning class = case when project type = 'Blow-cleaning class' then performance else 0 end,
Takeout = case when project type = 'takeout 'Then performance else 0 end,
Total = case when project type = 'Total' then performance else 0 end
From TB
Union all
Select project type = 'Commission ',
Blow-cleaning class = case when project type = 'Blow-washing class' then = else 0 end,
Takeout = case when item type = 'takeout 'Then Commission else 0 end,
Total = case when project type = 'Total' then Commission else 0 end
From TB
) M
Group by project type
Order by project type DESC
Drop table TB
/*
Total project categories
-----------------------------------------
Performance: 200, 100, 300
Commission 10 5 15
(The number of affected rows is 2)
*/
--------------------------------------------------------------------------
/*
The TB table in the database is as follows:
Monthly salary and benefits
January 10 0 200 300
February 11 0 210 310
March 12 0 220 320
April 13 0 230 330
What I want to get is
Project month-month
Salary 100 110 120 130
Benefits 200 210 220 230
300 310 320 330
That is to say, the rows and columns of the table are completely reversed, a bit like the rotating matrix. How can I implement it using SQL statements?
*/
If exists (select * From DBO. sysobjects
Where id = object_id (n' [DBO]. [p_zj] ') and objectproperty (ID, n' isprocedure') = 1)
Drop procedure [DBO]. [p_zj]
Go
/* -- General Stored Procedure for row and column swapping (Original: Batch creation): swaps the columns of a specified table according to the specified fields */
Create proc p_zj
@ Tbname sysname, -- Name of the table to be processed
@ Fdname sysname, -- used as the conversion column name
@ New_fdname sysname = ''-- specifies the column name for the converted Column
As
Declare @ S1 varchar (8000), @ S2 varchar (8000 ),
@ S3 varchar (8000), @ S4 varchar (8000 ),
@ S5 varchar (8000), @ I varchar (10)
Select @ S1 = '', @ S2 ='', @ S3 = '', @ S4 ='', @ S5 = '', @ I = '0'
Select @ S1 = @ S1 + ', @' + @ I + 'varchar (8000 )',
@ S2 = @ S2 + ', @' + @ I + '= ''' + case isnull (@ new_fdname, '') When ''then''
Else @ new_fdname + '= 'end + ''' + name + '''''''',
@ S3 = @ S3 + 'select @ '+ @ I +' = @ '+ @ I +' + '', ['' + ['+ @ fdname +
'] + ''] ='' + Cast ([' + name + '] As varchar) from [' + @ tbname + ']',
@ S4 = @ S4 + ', @' + @ I + '= ''select' + @' + @ I,
@ S5 = @ S5 + '+ ''union all'' + @' + @ I,
@ I = cast (@ I as INT) + 1
From syscolumns
Where object_id (@ tbname) = ID and name <> @ fdname
Select @ S1 = substring (@ S1, 2,8000 ),
@ S2 = substring (@ S2, 2,8000 ),
@ S4 = substring (@ S4, 2,8000 ),
@ S5 = substring (@ S5, 16,8000)
Exec ('desc' + @ S1 + 'select' + @ S2 + @ S3 + 'select' + @ S4 +'
Exec ('+ @ S5 + ')')
Go
-- Use the following stored procedure test:
Create Table Test (month varchar (4), salary int, benefit int, bonus INT)
Insert Test
Select 'february 11', 100,200,300 Union all
Select 'february 11', 110,210,310 Union all
Select 'february 11', 120,220,320 Union all
Select 'August 11', 130,230,330
Go
Exec p_zj 'test', 'month', 'project'
Drop Table Test
Drop proc p_zj
/*
Project month-month
------------------------------------------------
Benefits 200 210 220 230
Salary 100 110 120 130
300 310 320 330
(The number of affected rows is 3)
*/
/*
Static Statement (sql2005)
*/
-- Test environment
Create Table Test (month varchar (4), salary int, benefit int, bonus INT)
Insert Test
Select 'february 11', 100,200,300 Union all
Select 'february 11', 110,210,310 Union all
Select 'february 11', 120,220,320 Union all
Select 'August 11', 130,230,330
Go
-- Test statement
Select * from
(
Select evaluation month, month, amount from
(Select month, salary, benefits, bonus from test) P
Unregister
(Amount for assessment month in (salary, welfare, bonus) as unpvt
) T
Bytes
(Max (amount) for month in ([January], [February], [March], [April]) as PT
-- Test Result
/*
Assessment month-month
------------------------------
Welfare 200210220230
Salary: 100110120130
300310320330 Prize
*/
-- Delete the environment
Drop Table Test