Transformation
1. Row and column conversion--ordinary
Suppose there is a student record (CJ) as follows
Name Subject Results
John Language 80
John Math 90
John Physics 85
Dick Language 85
Dick Math 92
Dick Physics 82
Harry Math 60
Want to become
Name Language Mathematical Physical
Zhang 380 90 85
Lee 485 92 82
Harry NULL NULL
DECLARE @sql varchar (4000)
Set @sql = ' Select Name '
Select @sql = @sql + ', sum (case discipline when ' discipline ' ' then ') as ' discipline
From (select distinct discipline from CJ) as a
Set @sql = @sql ' from CJ Group by name '
EXEC (@sql)
2. Row and column conversions-merging
There are table A,
ID PID
1 1
1 2
1 3
2 1
2 2
3 1
How to make Table B:
ID PID
1 1,2,3
2 1,2
3 1
To create a merged function
Create function Fmerg (@id int)
Returns varchar (8000)
As
Begin
DECLARE @str varchar (8000)
Set @str = '
Select @str = @str ', ' cast (PID as varchar) from table A where id= @id
Set @str =right (@str, Len (@str)-1)
Return (@str)
End
Go
--Call the custom function to get the result
SELECT DISTINCT Id,dbo.fmerg (ID) from Table A