【问题标题】:Getting rid of duplicate values in my query摆脱查询中的重复值
【发布时间】:2018-08-20 22:07:31
【问题描述】:

我有一个看起来很简单的查询:

SELECT
event_time,
service_id,
order_id,
total_value,
purchase_type
FROM
order.table

同样,这是一个非常简单的查询。问题是,它会产生如下结果:

event_time     service_id   order_id   total_value purchase_type
8/19/18 16:18   305030       42549440   39.98       PVC 
8/19/18 16:09   305030       42549440   39.98       PCC

问题在于重复的order_id 号码。如果我想编写一个简单地采用较早的order_id 并摆脱较新版本的查询怎么办?作为记录,我尝试这样做MIN(event_time) OVER (PARTITION BY order_id) conversion_time,但它没有成功。我应该使用其他功能吗?

【问题讨论】:

  • 问题被关闭为“重复” - 但这个问题的答案与指定的不同。那里给出的答案是GROUP BY,但提出这个问题的人需要超越GROUP BY 并选择可能不是完全重复的完整行之一(最早的),而不是id。

标签: sql google-bigquery


【解决方案1】:

一种方法使用窗口函数,例如:

select o.*
from (select o.*, row_number() over (partition by order_id order by event_time) as seqnum
      from order.table o
     ) o
where seqnum = 1;

虽然这是“典型”方法,但另一种方法使用的资源更少:

select o.*
from (select o.*, min(event_time) over (partition by order_id) as min_event_time 
     from order.table o
     ) o
where min_event_time = event_time;

【讨论】:

    【解决方案2】:

    以下是 BigQuery 标准 SQL

    #standardSQL
    SELECT row.*
    FROM (
      SELECT ARRAY_AGG(t ORDER BY event_time LIMIT 1)[OFFSET(0)] row
      FROM `order.table` t
      GROUP BY order_id
    ) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2014-09-25
      • 1970-01-01
      相关资源
      最近更新 更多