Row and column conversions

Source: Internet
Author: User
Tags null null
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



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.