被复杂的 GROUP BY 难住了

问题描述 投票:0回答:1

给定以下查询,如何按

con_num
分组并使用 MAX
lead_id
检索
date_entered
?我正在使用 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

例如,当前查询返回(部分)以下两行...

lead_id 输入日期 con_num 订单日期
1 2021-04-20 N0226091 2021-04-22
2 2021-04-21 N0226091 2021-04-22

查询应为每个

con_num
返回一行,其中包含最新的
lead_id
及其
entered_date
...

lead_id 输入日期 con_num 订单日期
2 2021-04-21 N0226091 2021-04-22

谢谢你。

sql group-by sql-server-2012
1个回答
0
投票

使用

ROW_NUMBER()
窗口函数获取每个so.con_num的最新lead_id/date_entered行。

select lead_id, date_entered, con_num, ord_date
from
(
    SELECT leads.id AS lead_id 
        , leads.date_entered 
        , so.con_num 
        , so.ord_date
        , row_number() over (partition by so.con_num
                             order by lead_id desc, leads.date_entered desc) rn
    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
) dt
where rn = 1
© www.soinside.com 2019 - 2024. All rights reserved.