0

Kind of hard to explain, so I'll map it out. Given these four tables: houses, landlord_houses, company and tenant, I need to find all the houses that have signed up in the last 14 days and get some information about them.

Previously I've done this with a very simple select query from the houses table. But now I need to get the letting agent of the house to display on a report. The problem is, the letting agent can be in any one of 3 locations: in the company table, the houses table or in the tenant table. I've come up with this query so far:

select distinct h.id as id,
    h.address1 as address1,
    h.town as town,
    h.postcode as postcode,
    h.valid_from as valid_from,
    h.valid_to as valid_to,
    (CASE WHEN c.name IS NOT NULL THEN c.name || ' (MS)'
      WHEN h.letting_agent IS NOT NULL THEN h.letting_agent
      WHEN t.id IS NOT NULL THEN t.letting_agent
      ELSE 'Unknown (Not set yet)' END) AS agent
from houses h
left join landlord_houses lh on lh.house_id = h.id
left join company c on c.id = lh.company_id
left join tenant t on t.house_id = h.id
where h.deleted IS FALSE
and h.archived IS FALSE
and h.sign_up_complete IS TRUE
and h.completed > NOW() - '14 days'::INTERVAL
order by h.id

This kind of works, however I'm getting results back that have an empty agent field even though it's meant to say "Unknown (Not set yet)". I'm also getting duplicate houses returned even though I've used distinct h.id. I think this is because there are multiple letting agents for these houses in the company, houses and tenant tables.

What needs to be changed in the query to get this to work?

Thank you.

4

1 回答 1

-1

那个案例陈述看起来有点不靠谱。您可能会返回多个值。尝试这个:

COALESCE(c.name, h.letting_agent, t.letting_agent, 'Unknown (Not set yet)') as Agent

这将检查 c.name。如果它为空,则移至下一个参数并执行相同操作。

查询中的其他所有内容看起来都很好,这在 postgresql 中确实有效。

于 2013-07-18T14:45:58.887 回答