Trying to move multiple rows for each users to columns. There are different number of rows for some users, for instance, 2 or three emails, or 1 plus phone number. this differs depending on the user account.
Looks something like this.
Id FirstName LastName Listing phonetype listingTypeID
1 Judy Johnson judyJ@email.com null 4
1 Judy Johnson 555-555-2020 home 2
1 Judy Johnson 555-555-2022 home 2
1 Judy Johnson NULL null 1
2 Jim Brown 555-555-3333 cell 2
2 Jim Brown jbrown@email.com null 4
3 John White NULL null 1
3 John White johnwhite@email.com null 4
The null values represent the address, which I figured out how to do. I have seen this example quite a few times on stackflow, but not the variable number of rows per user. I realize that some columns will be empty for some users, but looking to get something like this.
Id FirstName LastName email email2 email3 phone phone2 phone3
1 Judy Johnson judyJ@email.com 555-555-2020 555-555-2022
2 Jim Brown jbrown@email.com jbrown33@info.com 555-555-3333 555-555-2332
3 John White jwhite@email.com
This is what I have and it works, but when there are multiple emails or phones with the same type (i.e., home or cell) there is no new column created. I'm thinking some type of If statement but can't figure it out.
SELECT id ,
firstname ,
lastname ,
middlename ,
prefix ,
suffix ,
notes ,
MAX(line1) address ,
MAX(line2) address2 ,
MAX(city) city ,
MAX(state) state ,
MAX(zip) zip ,
MAX(county) county ,
MAX(country) country ,
MAX(CASE WHEN phonetype = 'Cell' THEN listing END) Cell ,
MAX(CASE WHEN phonetype = 'Home' THEN listing END) Home ,
MAX(CASE WHEN phonetype = 'Office' THEN listing END) Office ,
MAX(CASE WHEN phonetype = 'Fax' THEN listing END) Fax ,
MAX(CASE WHEN listingTypeID = 4 THEN listing END) email ,
MAX(CASE WHEN listingTypeID = 5 THEN listing END) weblink
FROM [Matrix_Copy].[dbo].[Indiv]
GROUP BY id ,
firstname ,
lastname ,
middlename ,
prefix ,
suffix ,
notes
ORDER BY id
thanks for any help.