如何从左外连接中检索最大日期?

时间:2011-03-29 17:06:54

标签: mysql sql

我有2个表client_headquarter&客户端

client_headquarter: ID

客户端: id,headquarterid,clentname,tscreated

我想显示所有总部,并且每个总部都会显示“最近的”客户端(ts_created),如果它存在,则显示其中的空白。我希望所有这些都按照没有客户端,老客户端和底层最新客户端的总部进行排序。

有人可以协助查询吗?

3 个答案:

答案 0 :(得分:3)

SELECT client_headquarter.id, max(clients.tscreated)
FROM client_headquarter 
LEFT OUTER JOIN clients ON clients.headquarterid = client_headquarter.id
GROUP BY client_headquarter.id
ORDER BY MAX(clients.tscreated) ASC

答案 1 :(得分:0)

像...这样的东西。

> select chq.id, count(clientname), max(tscreated) from clients c
> left outer join client_headquarter chq on c.hearquarterid = chq.id
> group by chq.id
> order by count(clientname) DESC, max(tscreated) DESC

答案 2 :(得分:0)

select 
    ch.id as [Headquarter ID],
    c.clientname as [Most Recent Client Name],
    c.tscreated as [Date Created]
from 
    client_headquarter ch
    left join 
    (select 
        headquarterid,
        max(tscreated)
    from
        clients
    group by
        headquarterid
    ) recent on recent.headquarterid = ch.id
    left join clients c on c.headquarterid = ch.headquarterid and c.tscreated = recent.tscreated
order by
    c.tscreated

如果多个客户具有相同的创建日期,这将为单个总部创建多个行。如果这是不可取的,那么必须定义和实施一些区分胜利者的明确方法。

相关问题