简体   繁体   中英

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.

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM