如何根据 BigQuery 中的最新日期 return 每个客户一行?

How can I return one single row for each customer based on the latest date in BigQuery?

我有一个 table,其中包含以下结构中的数据。

customer_id;   status;   date
1;             1;       01-01-2019
1;            3;       01-02-2019
2;             4;        01-02-2019
2;             3;        01-03-2019

我想要return的是:

customer_id;   status;   date
1;            3;       01-02-2019
2;             3;        01-03-2019

到目前为止,我已经在日期的 select 子句中使用了 max 语句。

select    distinct customer_id,
          status,
          max(date) as date_max
from *table*
group by customer_id

这 return 是错误:意外的关键字 GROUP

希望对您有所帮助! 亲切的问候。

您想过滤数据,而不是汇总数据。这是您可以使用的一种方法:

select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.customer_id = t.customer_id
               );

在 BigQuery 中,您还可以:

select t.* except (seqnum)
from (select t.*, row_number() over (partition by customer_id order by date desc) as seqnum
      from t
     ) t;

或者,如果您想使用聚合:

select as value array_agg(t order by date desc limit 1)[offset(1)]
from t
group by customer_id;

这个查询应该这样做:

select t.customer_id, t.status, t.date
from YourTable t
inner join (select customer_id, max(date) as date
            from YourTable 
            group by customer_id) a
on (t.customer_id= a.customer_id and t.date = a.date)