views:

132

answers:

3

Hello, I have the following query:

SELECT     
  Base.ReportDate, 
  Base.PropertyCode, 
  Base.FirstName, 
  Base.MiddleName, 
  Base.LastName, 
  Person.FirstName, 
  Person.MiddleName, 
  Person.LastName
FROM  LeaseT INNER JOIN
   Base ON LeaseT.LeaseID = Base.LeaseID INNER JOIN
   Person ON LeaseT.TenantID = Person.ID

works fine, except there could be 0 to 'N' people in the 'Person' table for each record in the Base table, but I only want to return exactly 1 for each 'Base' record (doesn't matter which, but the one with the lowest Person.ID) would be a reasonable choice. If there is 0 rows in the person table, I still need to return the row, but with null values for the 'person' fields.

How would I structure the SQL to do that?

Thanks.

Edit: Yes, the tables are probably not structured properly, but restructuring at this time is not possible - got to work with what is there.

+1  A: 

Use a left join

HLGEM
+3  A: 

Following may be helpful to you

SELECT     
  Base.ReportDate, 
  Base.PropertyCode, 
  Base.FirstName, 
  Base.MiddleName, 
  Base.LastName, 
  d.FirstName, ou

  d.MiddleName, 
  d.LastName
FROM  LeaseT INNER JOIN
   Base ON LeaseT.LeaseID = Base.LeaseID INNER JOIN
left outer join   
 (select min(personid) as ID from person group by personid) as d 
on 
 LeaseT.TenantID = d.ID 
left outer join 
 (select FirstName, 
  MiddleName, 
  LastName from person) d1
on
  LeaseT.TenantID = d1.ID 
Pranay Rana
I guess LeaseT should be left-joined since it is the connection between Base and Person
devio
sorry to say but i am not getting you
Pranay Rana
+3  A: 

Does this work?

SELECT     
  Base.ReportDate, 
  Base.PropertyCode, 
  Base.FirstName, 
  Base.MiddleName, 
  Base.LastName, 
  Person.FirstName, 
  Person.MiddleName, 
  Person.LastName
FROM  Base
LEFT JOIN (
    SELECT LeaseID, MIN(TenantID) AS [TenantID]
    FROM LeaseT
    GROUP BY LeaseID) AS [LeaseT_SinglePerson] ON Base.LeaseID = [LeaseT_SinglePerson].LeaseID
LEFT JOIN Person ON [LeaseT_SinglePerson].TenantID = Person.ID
John Allers