presto / aws athena-选择记录的最新版本

时间:2018-08-31 15:16:36

标签: sql amazon-athena presto

我有一个订单事件表,每个订单完成后都包含很少的条目。一些订单被取消或退款。我试图选择状态为“ OrderConfirmed”的所有订单的最新版本,我以为我会使用以下SQL,但AWS Athena抱怨列“ latest_order_update.latest_update”无法解析。有任何线索吗?

WITH latest_order_update AS (
  SELECT orderevent_order.unique_id, MAX(orderevent_order.event_time) AS latest_update
  FROM orderevent_order
  GROUP BY orderevent_order.unique_id)
SELECT orderevent_order.unique_id
FROM orderevent_order
WHERE orderevent_order.event_time = latest_order_update.latest_update AND orderevent_order.header_event_name = 'OrderConfirmed'
LIMIT 10;

1 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER重写它:

WITH cte AS (
 SELECT oo.unique_id,
    ,ROW_NUMBER() OVER(PARTITION BY unique_id ORDER BY event_time DESC) rn
  FROM orderevent_order oo
)
SELECT * 
FROM cte
WHERE rn = 1;

或在FROM/JOIN /子查询中引用cte:

WITH latest_order_update AS (
  SELECT orderevent_order.unique_id, 
     MAX(orderevent_order.event_time) AS latest_update
  FROM orderevent_order
  GROUP BY orderevent_order.unique_id)
SELECT orderevent_order.unique_id
FROM orderevent_order
WHERE orderevent_order.event_time IN (SELECT l.latest_update 
                                      FROM latest_order_update l
                                      WHERE orderevent_order.unique_id 
                                         = l.unique_id)           
  AND orderevent_order.header_event_name = 'OrderConfirmed'
LIMIT 10;

加入:

WITH latest_order_update AS (
  SELECT orderevent_order.unique_id, 
     MAX(orderevent_order.event_time) AS latest_update
  FROM orderevent_order
  GROUP BY orderevent_order.unique_id)
SELECT orderevent_order.unique_id
FROM orderevent_order
JOIN latest_order_update
  ON orderevent_order.event_time = latest_order_update.latest_update
 AND orderevent_order.unique_id = latest_order_update.unique_id
WHERE orderevent_order.header_event_name = 'OrderConfirmed'
LIMIT 10;