LearnItFirst User Forum

New SQL Server 2008 DBA Course
Welcome Guest Search | New Posts | Members | Log In | Register

Using Pivot Operator Options
JacobPressures
Posted: Monday, October 05, 2009 12:00:51 PM
Rank: Newbie

Joined: 10/5/2009
Posts: 1
Points: 3
Where do you live?: Alabama
I'm trying to pivot the GuardianName so that each Guardian appears on a single row with the StudentID.

Currently the resultset looks like this:
SID GuardianName RN
608 Brian Johnson 1
608 Kristi Johnson 2
609 Joan Baer 1
610 Elaine Stevens 1
610 Mike Stevens 2
611 Kathy Taylor 1
611 Patricia McIntyre 2
612 Robert Madison 1
612 Theresa Madison 2


I want it to look like this:
SID Guardian1 Guardian2
608 Brian Johnson Kristi Johnson
609 Joan Baer
610 Elaine Stevens Mike Stevens
611 Kathy Taylor Patricia McIntyre
612 Robert Madison Theresa Madison



However, I get an error such as this:

Quote:
Msg 156, Level 15, State 1, Line 20
Incorrect syntax near the keyword 'FOR'.


What am I doing wrong?
Also, is it against the rules to have a JOIN statement at all in the main query when using PIVOT?

Code:

;
WITH  Guardian
AS
(
    SELECT
     sc.StudentID,
     GuardianName=REPLACE(scp.FirstName + ' ' + scp.LastName,',',' '),

     ROW_NUMBER() OVER(PARTITION BY sc.StudentID ORDER BY addr.State DESC, scp.LastName, scp.FirstName) AS rn

    FROM StudentContact sc
        INNER JOIN Person scp ON scp.PersonID = sc.ContactID
        LEFT OUTER JOIN Address addr ON addr.AddressID = scp.MailingAddressID
        LEFT OUTER JOIN PersonTelephone pt ON pt.PersonID = scp.PersonID AND pt.IsPrimary = 'True'
    WHERE sc.IsCustodian = 1 
)
select *
from guardian

PIVOT (
FOR RN
IN ([1], [2])

) AS pvt


Scott Whigham
Posted: Friday, October 09, 2009 1:53:09 PM


Rank: Super Mod

Joined: 3/20/2006
Posts: 460
Points: 1,002
Where do you live?: Dallas, TX
The reason your query fails is that your PIVOT does not have an aggregate, which is required. I supposed you could add in the MAX() agg but I'm not sure PIVOT is right here.
Code:
PIVOT (
MAX(GuardianName)
FOR RN
IN ([1], [2])
)
bklr
Posted: Monday, December 28, 2009 12:54:05 AM

Rank: PFY

Joined: 1/21/2009
Posts: 27
Points: 81
Where do you live?: India
go through this link
http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.