如果指定了DISTINCT,则不允许BigQuery窗口使用ORDER BY

Sco*_*age 1 window-functions google-bigquery bigquery-standard-sql

我正在调查移植一些像这样的窗口化不同计数的bigquery传统sql

count(distinct brand_id) over (partition by user_id order by order_placed_at range between 7 * 24 * 60 * 60 * 1000000 PRECEDING AND 1 PRECEDING) as last_7_day_buyer_brands

到标准SQL。...但是我得到这个错误。

Window ORDER BY is not allowed if DISTINCT is specified

作为参考,我尝试过APPROX_COUNT_DISTINCT没有运气的函数。

除了编写子查询和分组依据以外,还有其他更好的方法可以使它工作吗?

其他大多数查询只进行了少量更改就移植到了标准sql。

Mik*_*ant 6

每个文档

OVER子句要求:

分区依据:可选。
ORDER BY:可选。如果存在DISTINCT,则不允许使用。
window_frame_clause:可选。如果存在DISTINCT,则不允许使用

注意:以上是我“突出显示”的内容,而不是文档中的内容

正如你不仅可以看到ORDER BY但即使RANGE BETWEEN时不允许DISTINCT使用

我认为,子查询是必经之路。

如果您需要指导,请使用以下简单示例

#standardSQL
SELECT
  user_id,
  order_placed_at,
  brand_id,
  (SELECT COUNT(DISTINCT brand) 
      FROM UNNEST(last_7_day_buyer_brands_with_dups) AS brand
  ) AS last_7_day_buyer_brands
FROM (
  SELECT 
    user_id,
    order_placed_at,
    brand_id,
    ARRAY_AGG(brand_id) OVER(
      PARTITION BY user_id ORDER BY order_placed_at 
      RANGE BETWEEN 7 * 24 * 60 * 60 * 1000000 PRECEDING AND 1 PRECEDING
    ) AS last_7_day_buyer_brands_with_dups
  FROM yourTable
)
Run Code Online (Sandbox Code Playgroud)