Transposing rows to column in sql server

Posted on 2012-08-16
Medium Priority
Last Modified: 2012-08-16
I need a help.

I have a table where the marks are getting inserted.

RollNo | PaperCode | Marks
A         | 1                |45
A         | 2                |26
A         | 4                |30
B         | 2                |98
B         | 3                |58

I want the result in a table in this way:

RollNo | 1   |2   |3   |4  
A         | 45 |26 | 0  |30
B         |   0  |98 |58 |0

Please help me how can I do like this.

Question by:sam000
  • 2
LVL 25

Expert Comment

ID: 38299603
LVL 25

Accepted Solution

lwadwell earned 1500 total points
ID: 38299618
Two methods:
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL 
      DROP TABLE #tmp
create table #tmp (
    RollNo          char(1),
    PaperCode       int,
    Marks           int
insert into #tmp values 
('A', 1, 45),('A', 2, 26),('A', 4, 30),('B', 2, 98),('B', 3, 58)

-- using CASE statements
select rollno, 
       sum(case PaperCode when 1 then Marks else 0 end) as [1],
       sum(case PaperCode when 2 then Marks else 0 end) as [2],
       sum(case PaperCode when 3 then Marks else 0 end) as [3],
       sum(case PaperCode when 4 then Marks else 0 end) as [4]
from #tmp
group by rollno

-- using PIVOT
select rollno, [1], [2], [3], [4]
from #tmp
pivot (sum(Marks) for Papercode in ([1], [2], [3], [4])) p

Open in new window


Author Comment

ID: 38299631

Author Closing Comment

ID: 38299880
nice reply

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Suggested Courses

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question