SQL Server row to column

Source: Internet
Author: User

Interview encountered a recent interview problem, suddenly a little confused, only to say the idea, then Baidu a bit, collated a bit of ideas, so record down, easy to learn later. (see attachment for questions)

Related Data sheets:

1.Score table

2.[user] Table

The SQL statements are as follows:

--Method one: Static SQL
SELECT * FROM
(SELECT uid,name, score,scorename from Score,[user] WHERE score.uid=[user].id) As SourceTable
PIVOT (AVG (score) for Scorename in ([English], [math])) as a

--Method two: Dynamic SQL
DECLARE @s NVARCHAR (4000)
SELECT @s = ISNULL (@s + ', ', ') + QUOTENAME (scorename)
From (select distinct scorename from score) as A---column names do not repeat

Declare @sql NVARCHAR (4000)
SET @sql = '
Select r.* from
(select Uid,name,scorename,score from Score,[user] where score.uid=[user].id) as T
Pivot
(
Max (T.score)
For T.scorename in (' +@s+ ')
) as R '
EXEC (@sql)

--Method Three: case when
Select
Row_number () over (ORDER by [user].id) as number,
UID as user number,
Name as names,
Max (case scorename when ' English ' then score else 0 end) English,
Max (case scorename when ' math ' then score else 0 end) Math
From Score,[user] WHERE score.uid=[user].id
GROUP BY Uid,[user].id,name

Related Article

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.