我有以下查询:
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
工作正常,除了Base表中每个记录的'Person'表中可能有0到'N'个人,但我只想为每个'Base'记录返回1个(无关紧要) ,但Person.ID最低的那个将是一个合理的选择。如果人员表中有0行,我仍然需要返回该行,但“人员”字段的值为空。
我如何构建SQL来做到这一点?
感谢。
编辑:是的,这些表可能没有正确构建,但此时无法进行重组 - 可以使用那里的内容。
答案 0 :(得分:3)
以下可能对您有所帮助
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
答案 1 :(得分:3)
这有用吗?
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
答案 2 :(得分:1)
使用左连接