Given the following query, how do I group by con_num
and retrieve the lead_id
with the MAX date_entered
? I am using SQL Server 2012.
SELECT leads.id AS lead_id
, leads.date_entered
, so.con_num
, so.ord_date
FROM crm.leads
INNER JOIN crm.contacts ON leads.contact_id = contacts.id
INNER JOIN crm.email_addr_bean_rel rel ON rel.bean_id = contacts.id
INNER JOIN crm.email_addresses email ON email.id = rel.email_address_id
INNER JOIN sales_order so ON so.bill_email = email.email_address OR so.dt_email = email.email_address
WHERE rel.bean_module = 'contacts' AND so.ord_date >= leads.date_entered
For example, the current query returns (in part) the following two rows…
|lead_id |date_entered |con_num |ord_date |
|————————————|——————-|——–|——————-|
|C9EC94E7-6202-4B9D-BF59-06121B2C6DB3|2021-04-20 15:19:16|N0226091|2021-04-22 00:00:00|
|7E986431-5DAB-4C8A-9A52-EB37581F2629|2021-04-21 18:19:04|N0226091|2021-04-22 00:00:00|
I want the query to return one row per con_num
that contains the latest lead_id
along with its entered_date
…
|lead_id |date_entered |con_num |ord_date |
|————————————|——————-|——–|——————-|
|7E986431-5DAB-4C8A-9A52-EB37581F2629|2021-04-21 18:19:04|N0226091|2021-04-22 00:00:00|
Thank you.