SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Combining multiple rows to return one row
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Niki
Yak Posting Veteran

51 Posts

Posted - 11/27/2012 :  18:22:19  Show Profile  Reply with Quote
I need to extract data into one record per student from a table that stores data in multiple rows. How do I do that? Please help.

DECLARE @Student TABLE
(
StudentNo INT NOT NULL,
TestDate Datetime,
Subject char(10),
Score int
)

INSERT @Student VALUES
(1, ‘20010515’, ‘Read’,’600’),
(1, ‘20010515’, ‘Write,’700’),

I wish it to return a record with -
StudentNo, Testdate, read_score, Write_score
1 20010515 600 700
Where I populate the scores based on the 'Subject' in my table.

Niki

Edited by - Niki on 11/27/2012 18:29:06

Bustaz Kool
Flowing Fount of Yak Knowledge

USA
1690 Posts

Posted - 11/27/2012 :  19:19:47  Show Profile  Reply with Quote
I think that you want to use the PIVOT operator. Look it up in BOL and see if that will work for you.

=================================================
Hear the sledges with the bells - silver bells!
What a world of merriment their melody foretells!

Edited by - Bustaz Kool on 11/27/2012 19:27:38
Go to Top of Page

sodeep
Flowing Fount of Yak Knowledge

USA
7174 Posts

Posted - 11/27/2012 :  19:41:18  Show Profile  Reply with Quote
OR

Select StudentNo,TestDate,
MAX(Case When Subject = 'Read' then Score End)Read_Score,
MAX(Case When Subject = 'Write' then Score End)Write_Score
from @Student
Group by StudentNo,TestDate
Order by StudentNo,TestDate
Go to Top of Page

sodeep
Flowing Fount of Yak Knowledge

USA
7174 Posts

Posted - 11/27/2012 :  19:53:59  Show Profile  Reply with Quote
OR this

Select distinct StudentNo,TestDate,
MAX(Case When Subject = 'Read' then Score End) OVER (PARTITION BY StudentNo,TestDate),
MAX(Case When Subject = 'Write' then Score End) OVER (PARTITION BY StudentNo,TestDate)
from @Student
Go to Top of Page

Niki
Yak Posting Veteran

51 Posts

Posted - 11/28/2012 :  12:07:21  Show Profile  Reply with Quote
Thank you, sodeep! It worked perfectly.

Niki
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000