首页 > 解决方案 > Postgres - 检索内部连接最旧的记录

问题描述

因此,在我的工作中,管理层想要评估我们联系潜在客户需要多长时间。在 1 小时之前、1 到 3 小时之间等联系了多少潜在客户。

通过此查询,我可以接近结果,但如果多次联系该潜在客户(这是最常见的情况),则结果会出现偏差,例如: - 潜在客户在 9:00 进入广告,在 9:30 获得联系,为“1 小时前”列计数一个,然后它随后被联系 N 次,因此该事件将计入所有不同的列。我想要的只是第一次接触。

有没有办法INNER JOIN只考虑最早的联系方式,即与我们相关的信息?

ws_ts是主角timestamp并且call_start是不言自明的。线索表并call_logs加入contact_id

提前致谢。我的选择:

    select 
    min(dcl.call_start::date) as Date, 
    sum(
        case
            when (((dcl.call_start) - (lsl.ws_ts))::interval) < '01:00:00'
            then 1
            else 0 
                end

    )as "Lead called before 1 hour",

    sum(
        case
            when ((  ((dcl.call_start) - (lsl.ws_ts)))::interval) > '01:00:00' and ((  ((dcl.call_start) - (lsl.ws_ts)))::interval)  < '03:00:00'
            then 1
            else 0 
                end

    )as "Lead called between 1 and 3 hours",


    sum(
        case
            when ((  ((dcl.call_start) - (lsl.ws_ts)))::interval) > '03:00:00' and ((  ((dcl.call_start) - (lsl.ws_ts)))::interval)  < '05:00:00'
            then 1
            else 0 
                end

    )as "Lead called between 3 and 5 hours",

    sum(
        case
            when ((  ((dcl.call_start) - (lsl.ws_ts)))::interval) > '05:00:00' 
            then 1
            else 0  
                end

    )as "Lead called after 5 hours"


    from public.leads lsl 
    inner join dialer.dialer_call_logs dcl on (lsl.ws_contact_id::int = dcl.contact_id )
    where lsl.ws_source = 'CAMPAIGN'  and lsl.ws_ts::date between '2020-03-09' and '2020-03-13' and lsl.ws_type <> 'call' and dcl."source" = 'CAMPAIGN'
    group by lsl.ws_creation

我得到的结果:

|Date|Lead called before 1 hour|Lead called between 1 and 3 hours|Lead called between 3 and 5 hours|Lead called after 5 hours|
|---|---------------------------------------|--------------------------------------|--------------------------------------|-------------------------------------|
|2020-03-09|118|32|23|426|
|2020-03-10|119|21|26|455|
|2020-03-11|154|39|28|667|
|2020-03-12|146|28|23|442|
|2020-03-13|72|20|21|223|

标签: sqlpostgresql

解决方案


一种方法是横向连接:

from public.leads lsl cross join lateral
     (select dcl.*
      from dialer.dialer_call_logs dcl 
      where ws_contact_id::int = contact_id
      order by dcl.call_start asc
      limit 1
     ) dcl
where ws_source = 'CAMPAIGN' and
      ws_ts::date between '2020-03-09' and '2020-03-13' and
      ws_type <> 'call' and dcl."source" = 'CAMPAIGN'

您尚未指定列的来源。某些where条件可能需要在子查询中。


推荐阅读