[英]Self joining table view
I have a table containing non-unique leads, which I need to group to contain unique, most recent (column date
) leads. 我有一个包含非唯一潜在客户的表,我需要对其进行分组以包含唯一的,最新的(列date
)潜在客户。
id lead_id status date
----- ------ -- -------------------
26199 666842 Ok 2013-06-19 12:00:09
56199 376842 Ok 2013-06-19 12:00:09
58322 376842 Ok 2013-06-21 12:11:59
60357 376842 Ok 2013-06-24 12:22:00
61431 376842 Ok 2013-06-25 12:18:02
62365 376842 Ok 2013-06-26 12:16:04
63202 376842 Ok 2013-06-27 12:14:08
63983 376842 Er 2013-06-28 12:12:06
So in the example above I should have two leads as a result: id 26199
and 63983
as they both are the ones with MAX(date)
while being GROUP BY
lead_id. 所以在上面的例子中,我应该有两根引线的结果:编号26199
和63983
,因为他们都是与那些MAX(date)
,同时GROUP BY
lead_id。
I tried with left joins, max and group aggregation, don't know what I'm doing wrong. 我尝试了左联接,最大和组聚合,不知道我在做什么错。
SELECT a.lead_id, MAX(a.created) AS created FROM RawLead a LEFT JOIN RawLead b ON b.created = a.created GROUP BY a.lead_id
Unfortunatelly I cannot use subqueries, cause I need to present them in the view. 不幸的是,我无法使用子查询,因为我需要在视图中显示它们。
No subqueries :) 没有子查询:)
select
l1.*
from
lead l1
left join lead l2 on l1.date < l2.date and l1.lead_id = l2.lead_id
where l2.id is null
See it working live in an sqlfiddle . 看到它在sqlfiddle中实时工作。
The LEFT JOIN works on the basis that when l1.date is at its maximum value, there is no l2.date with a greater value and the l2 rows values will be NULL. LEFT JOIN的工作原理是,当l1.date为最大值时,不存在更大的l2.date且l2行的值将为NULL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.