I have the 3 raw data tables below, and would like to extract some
data. My current query is really cumbersome, does anyone know a better
way to get all the info (attach the right state to the lowest zip code)
in one step? Thanks a lot! Here are the details.
- Ideal Output, for each person , keep
(1) person_id (From Table A)
(2) The earliest open_date of accounts starting with 2 (From Table A)
(3) ssn (From Table B)
(4) Zip and state info (From Table C), but only keep the lowest zip and
state.
-Table A -
person_id account open_date
10001 22000001 5/15/2003
10001 22000002 6/20/2004
10001 30000001 2/2/2002
10002 22000003 8/12/2004
10002 22000004 9/15/2004
10002 30000002 2/16/2005
-Table B -
person_id zip state
10001 11111 AA
10001 22222 CC
10002 33333 BB
--Table C -
person_id ssn
10001 1234567
10002 2345678
-Ideal Output-
person_id min_open ssn zip state
10001 5/15/2003 1234567 11111 AA
10002 8/12/2004 2345678 33333 BB
Here is what I did:
Select a.person_id, min(a.open_date), b.ssn, min(c.zip) as zip
,cast (0 as varchar) as state
Into output
From TableA as a Join TableB as b
on a.person_id=b.person_id
Join TableC as c
on a.person_id=c.person_id
Where a.account like '2%'
Group by a.person_id, b.ssn
Order by a.person_id
Update output
Set output.state=b.stateFrom output as a
Join TableC as b
on a.person_id=b.person_id
and a.zip=b.zip