1

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.

2
  • 1
    What database? This is the 'max from group' again, except instead of max you want min. Commented May 13, 2010 at 18:12
  • What exactly are you trying to do, just return one random person from each base? The way you have it now, I think it is going to return every single person no matter what you do since the person fields are in the select. Commented May 13, 2010 at 18:17

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

3

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 

2 Comments

I guess LeaseT should be left-joined since it is the connection between Base and Person
sorry to say but i am not getting you
1

Use a left join

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.