Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase ««12

SQL Query to select one row and fill missing columns from another matching row. Expand / Collapse
Author
Message
Posted Tuesday, October 2, 2012 4:57 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 6:01 PM
Points: 3,609, Visits: 5,222
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!
Post #1366959
Posted Tuesday, October 2, 2012 5:01 AM


Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Friday, June 27, 2014 8:03 AM
Points: 320, Visits: 1,079
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;



Post #1366962
Posted Tuesday, October 2, 2012 5:03 AM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 6:01 PM
Points: 3,609, Visits: 5,222
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.


Didn't look at the setup data.



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!
Post #1366963
Posted Tuesday, October 2, 2012 6:06 AM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Friday, July 4, 2014 3:55 AM
Points: 2,836, Visits: 5,062
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!"
(So many miracle inventions provided by MS to us...)

How to post your question to get the best and quick help
Post #1366978
Posted Tuesday, October 2, 2012 7:03 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 6:01 PM
Points: 3,609, Visits: 5,222
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!
Post #1367366
« Prev Topic | Next Topic »

Add to briefcase ««12

Permissions Expand / Collapse