SQL Presto查询-是否检索所有可能的行组合?

时间:2019-03-11 16:55:24

标签: sql combinations data-analysis presto

我想知道如何将交叉联接表的所有可能组合都获得给自己?

样本表如下

    DAY   Order  pickup_lat  pickup_long     dropoff_lat dropoff_long  created_time
 1/3/19  234e    32.69        -117.1          32.63      -117.08   3/1/19 19:00
 1/3/19  235d    40.73        -73.98          40.73       -73.99   3/1/19 23:21
 1/3/19  253w    40.76        -73.99          40.76       -73.99   3/1/19 15:26
 2/3/19  231y    36.08        -94.2           36.07       -94.21   3/2/19 0:14
 3/3/19  305g    36.01        -78.92          36.01       -78.95   3/2/19 0:09
 3/3/19  328s    36.76        -119.83         36.74       -119.79  3/2/19 4:33
 3/3/19  286n    35.76        -78.78          35.78       -78.74   3/2/19 0:43

我想查看订单的所有可能组合,这些订单组合基于订单创建时间和距离(以英里为单位)的差异,包括提货和提货。这可能吗?

我将使用great_circle_distance(pickup_lat,pickup_lng, pickup_1_lat, pickup_1_lng)*0.621371)来计算彼此之间的距离以及上下车的距离。

date_diff('minute', created_time, created_time_1) as order_creation_delta

因此,类似的任何两个订单或成对的订单,都是在彼此3分钟之内创建的,并且彼此之间的取货地点相距3英里,而彼此的下车地点相距3英里。

    with data as 
( select
    a.business_day,
        a.delivery_uuid,
        a.order_created_time_utc,
        a.pickup_lat,
        a.pickup_lng,
        a.dropoff_lat,
        a.dropoff_lng
from integrated_delivery.managed_delivery_fact a
where a.business_day between (timestamp '2019-03-01') and (timestamp '2019-03-03')
    union
    select b.business_day as b_business_day,
        b.delivery_uuid as b_delivery_uuid,
        b.order_created_time_utc as b_order_created_time_utc,
        b.pickup_lat as b_pickup_lat,
        b.pickup_lng as b_pickup_lng,
        b.dropoff_lat as b_dropoff_lat, 
        b.dropoff_lng as b_dropoff_lng
from integrated_delivery.managed_delivery_fact b
where b.business_day between (timestamp '2019-03-01') and (timestamp '2019-03-03')
)

stats as 
( select abs(date_diff('minute', a.order_created_time_utc, b.order_created_time_utc)) as order_creation_difference,
         (great_circle_distance(a.pickup_lat, a.pickup_lng, b.pickup_lat, b.pickup_lng)*0.621371) as pickup_distance,
         (great_circle_distance(a.dropoff_lat, a.dropoff_lng, b.dropoff_lat, b.dropoff_lng)*0.621371) as dropoff_distance
from data
)
select a.delivery_uuid, b.delivery_uuid, order_creation_difference, pickup_distance, dropoff_distance
    from data a
        cross join data b  
        WHERE a.delivery_uuid <> b.delivery_uuid
        and order_creation_difference <3
        and pickup_distance < 3
        and dropoff_distance <3

我有类似上面的查询,但是不确定如果我先合并表,是否可以将值计算为cte?

1 个答案:

答案 0 :(得分:0)

似乎您需要进行联接而不是联合。

with a as (select * from your_table)
select * from your_table
inner join a on 
great_circle(a.lat, a.long, your_table.lat, your_table.long) < max_dist
and abs(date_diff('min', a. date, your_table. date)) < max_time

说明:两个表的inner join输出on之后的条件为true的所有行和仅行组合。您可能还希望施加最小距离,以排除一行与自身的匹配项。