I am working on modifying a view and I’m stuck.
My user has an old program that queries a database view that has parent (mother and father) data. The mother’s and father’s name shared a single record (id, fname, lname, fname2, lname2, etc…).
I built a new database and the table and corresponding view was changed to have user_id, parent_id, fname, and lname.
Parents share a user_id but have individual parent_id.
Anyway, I am trying to get results from (user_id, fname, lname) back to looking like (id, fname, lname, fname2, lname2) and got stuck. I wasn’t sure where to start so I got to the following code:
This is what I start with (excluding the parent_id):
user_id fname lname expiration
4 Jane Doe 2015-01-01 00:00:00.000
4 John Doe 2015-01-01 00:00:00.000
5 Bill Smith 2015-01-01 00:00:00.000
5 Mary Smith 2015-01-01 00:00:00.000
This is the sql I am trying and got stuck with:
SELECT ROW_NUMBER() OVER ( PARTITION BY parents.user_id ORDER BY parents.user_id ASC ) RowVersion ,
dbo.parents.user_id ,
fname ,
lname ,
'' AS fname2 ,
'' AS lname2 ,
ExpirationDate AS 'expiration'
FROM dbo.parents
INNER JOIN dbo.payment ON dbo.parents.user_id = dbo.payment.User_Id
UNION
SELECT ROW_NUMBER() OVER ( PARTITION BY parents.user_id ORDER BY parents.user_id ASC ) RowVersion ,
dbo.parents.user_id ,
'' AS fname ,
'' AS lname ,
fname AS fname2 ,
lname AS lname2 ,
ExpirationDate AS 'expiration'
FROM dbo.parents
INNER JOIN dbo.payment ON dbo.parents.user_id = dbo.payment.User_Id
GROUP BY parents.user_id ,
fname ,
lname ,
ExpirationDate
This is the result of above sql;
RowVersion user_id fname lname fname2 lname2 expiration
1 4 John Doe 2015-01-01 00:00:00.000
1 4 Jane Doe 2015-01-01 00:00:00.000
2 4 Jane Doe 2015-01-01 00:00:00.000
2 4 John Doe 2015-01-01 00:00:00.000
1 5 Bill Smith 2015-01-01 00:00:00.000
1 5 Mary Smith 2015-01-01 00:00:00.000
2 5 Mary Smith 2015-01-01 00:00:00.000
2 5 Bill Smith 2015-01-01 00:00:00.000
This is what I need:
user_id fname lname fname2 lname2 expiration
4 Jane Doe John Doe 2015-01-01 00:00:00.000
5 Bill Smith Mary Smith 2015-01-01 00:00:00.000
I feel like I’m close but I also feel like I went down the wrong road. Any suggestions?
This should do: