Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


SQL Query to select one row and fill missing columns from another matching row.


SQL Query to select one row and fill missing columns from another matching row.

Author
Message
dwain.c
dwain.c
SSCarpal Tunnel
SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)

Group: General Forum Members
Points: 4291 Visits: 6431
kk 93815 (10/2/2012)
Thanks laurie. we are using 2005


I think both solutions should run on SQL 2005.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
laurie-789651
laurie-789651
SSC-Addicted
SSC-Addicted (424 reputation)SSC-Addicted (424 reputation)SSC-Addicted (424 reputation)SSC-Addicted (424 reputation)SSC-Addicted (424 reputation)SSC-Addicted (424 reputation)SSC-Addicted (424 reputation)SSC-Addicted (424 reputation)

Group: General Forum Members
Points: 424 Visits: 1271
This will work in 2005. Only the test data has changed (& variable declaration).

Please note: You should post on a 2005 forum for 2005 answers :-)




--===== TEST DATA =========
declare @Person table
(Id int, Name varchar(20), MartialStatus int, EmploymentStatus int, Email varchar(50), JobId int );

INSERT INTO @Person
( Id, Name, MartialStatus, EmploymentStatus, Email, JobId )
VALUES
(1, 'John', 8, 6, 'John@xxx.com', 99);
INSERT INTO @Person
( Id, Name, MartialStatus, EmploymentStatus, Email, JobId )
VALUES
(2, 'John', 10, 7, 'John@xxx.com', 100);
INSERT INTO @Person
( Id, Name, MartialStatus, EmploymentStatus, Email, JobId )
VALUES
(3, 'John', NULL, NULL, 'John@xxx.com', 101);
INSERT INTO @Person
( Id, Name, MartialStatus, EmploymentStatus, Email, JobId )
VALUES
(4, 'Max', 6, 5, 'max@emailreaction.org', 102);

--select * from @Person

declare @Job table
(JobId int, GroupId int, [Desc] varchar(30) );

INSERT INTO @Job
( JobId, GroupId, [Desc] )
VALUES
(99, 50, 'blah blah');
INSERT INTO @Job
( JobId, GroupId, [Desc] )
VALUES
(100, 50, 'blah blah');
INSERT INTO @Job
( JobId, GroupId, [Desc] )
VALUES
(101, 50, 'blah blah');
INSERT INTO @Job
( JobId, GroupId, [Desc] )
VALUES
(102, 51, 'blah blah');

--select * from @Job

--I want to retrieve a record from the person table based on the group id...
--for eg. for Group Id 50 I want the following record which is mix of record 3 and 2 as:
--------------------------------------
--3, John,10,7,John@xxx.com,101
---------------------------------------

--Record num 3 should be retrieved with the marital status and employment status from record two as they were null.

--====== SUGGESTED SOLUTION =========
declare @GroupId int;
set @GroupId = 50;

with CTE as
(
select
RowId = ROW_NUMBER() over (partition by p.Name order by p.JobId desc),
p.Id,
p.Name,
p.MartialStatus,
p.EmploymentStatus,
p.Email,
p.JobId
from @job j
inner join @Person p on j.jobId = p.JobId
where j.GroupId = @GroupId
)
select a.Id,
a.Name,
MartialStatus = coalesce(a.MartialStatus,b.MartialStatus,c.MartialStatus),
EmploymentStatus = coalesce(a.EmploymentStatus,b.EmploymentStatus,c.EmploymentStatus),
a.Email,
a.JobId
from CTE a
left outer join CTE b on a.RowId +1 = b.RowId
left outer join CTE c on a.RowId +2 = c.RowId
where a.RowId = 1;




dwain.c
dwain.c
SSCarpal Tunnel
SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)

Group: General Forum Members
Points: 4291 Visits: 6431
dwain.c (10/2/2012)
kk 93815 (10/2/2012)
Thanks laurie. we are using 2005


I think both solutions should run on SQL 2005.


w00tHehe:w00tBigGrinidn't look at the setup data.Hehew00tHehe


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
Eugene Elutin
Eugene Elutin
Hall of Fame
Hall of Fame (3K reputation)Hall of Fame (3K reputation)Hall of Fame (3K reputation)Hall of Fame (3K reputation)Hall of Fame (3K reputation)Hall of Fame (3K reputation)Hall of Fame (3K reputation)Hall of Fame (3K reputation)

Group: General Forum Members
Points: 3046 Visits: 5478
Question to OP: Can the name change? - If yes, you cannot partition by name.
Numbers for MartialStatus and EmploymentStatus can change from higher to lower, therefore you cannot really use MAX(), as I believe what you really want to see is the latest non-null value for them.
Can Email be NULL? If so, than it should be some logic for email as well.

_____________________________________________
"The only true wisdom is in knowing you know nothing"
"O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
(So many miracle inventions provided by MS to us...)

How to post your question to get the best and quick help
dwain.c
dwain.c
SSCarpal Tunnel
SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)

Group: General Forum Members
Points: 4291 Visits: 6431
I thought it might be interesting to approach this with a recursive CTE, such as the following. Try this setup data:


declare @Person table
(Id int IDENTITY, Name varchar(20), MartialStatus int
,EmploymentStatus int, Email varchar(50), JobId int );

INSERT INTO @Person ( Name, MartialStatus, EmploymentStatus, Email, JobId )
SELECT 'John', 8, 6, 'John@xxx.com', 99
UNION ALL SELECT 'John', 10, 7, 'John@xxx.com', 100
UNION ALL SELECT 'John', NULL, NULL, 'John@xxx.com', 101
UNION ALL SELECT 'Max', 6, 5, 'max@emailreaction.org', 102
UNION ALL SELECT 'Dwain', NULL, 5, 'dwain@ssc.com', 103
UNION ALL SELECT 'Dwain', 6, 2, 'dwain@ssc.com', 104
UNION ALL SELECT 'Dwain', NULL, 10, 'dwain@yahoo.com', 105

--select * from @Person

declare @Job table (JobId int, GroupId int, [Desc] varchar(30) );

INSERT INTO @Job ( JobId, GroupId, [Desc] )
SELECT 99, 50, 'blah blah'
UNION ALL SELECT 100, 50, 'blah blah'
UNION ALL SELECT 101, 50, 'blah blah'
UNION ALL SELECT 102, 51, 'blah blah'
UNION ALL SELECT 103, 52, 'blah blah'
UNION ALL SELECT 104, 52, 'blah blah'
UNION ALL SELECT 105, 52, 'blah blah'




And this script:


;WITH Grouper AS (
SELECT Id, Name, MartialStatus, EmploymentStatus, Email, a.JobId, GroupId
,n=ROW_NUMBER() OVER (PARTITION BY GroupID ORDER BY Id DESC)
FROM @Person a
INNER JOIN @Job b ON a.JobId = b.JobId
),
PickLast AS (
SELECT Id, Name, MartialStatus, EmploymentStatus, Email, JobId, GroupId, n
FROM Grouper
WHERE n = 1
UNION ALL
SELECT a.Id, a.Name
,ISNULL(b.MartialStatus, a.MartialStatus)
,ISNULL(b.EmploymentStatus, a.EmploymentStatus)
,ISNULL(b.Email, a.Email)
,a.JobId, a.GroupId, a.n
FROM Grouper a
INNER JOIN PickLast b ON a.GroupID = b.GroupID AND
a.n = b.n + 1
WHERE b.MartialStatus IS NULL OR b.EmploymentStatus IS NULL OR b.Email IS NULL
)
SELECT Id, Name, MartialStatus, EmploymentStatus, Email, JobId, GroupId
FROM (
SELECT Id, Name, MartialStatus, EmploymentStatus, Email, JobId, GroupId
,n=ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY n DESC)
FROM PickLast) a
WHERE n = 1




The PickLast rCTE loops through the records picking up the latest non-null value for each of the 3 fields: email, marital status (which is misspelled by the way) and employment status. So now it doesn't matter how many records there are. Only that there is a unique identifier that specifies the order of insertion (I made Id IDENTITY for that reason).


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search