Bigquery - 当 window 函数具有所有相同的值时如何只获得一个最大值
Bigquery - How to get only one max value when a window function has all the same values
我在 Google BigQuery 中使用 window 函数来获取客户的最大价值,如下所示:
SELECT customer_key, store_location,
FIRST_VALUE(store_key) OVER (
PARTITION BY customer_key
ORDER BY visits DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS fav_store
FROM VISIT_DB
ORDER BY customer_key ASC
它让我的商店有更多的顾客光顾,效果很好。但是,在某些情况下,客户在 3 个不同商店的访问次数相同,并且此函数 return 具有相同的 3 个值。
例如,当顾客 111 在商店 A、B 和 C 有 3 次光顾时,因为它们都有相同的光顾次数,我希望他们中的任何一个都被 returned 而不是全部三个他们。
我也试过用LAST_VALUE
和MAX
但是当访问量相同的时候,他们三个return所有的店。
我怎样才能让它 return 只有一个?
我能够使用此脚本获得预期的输出:
SELECT customer_key, store_location, store_key as fav_store
FROM (
SELECT *, ROW_NUMBER() OVER(partition by customer_key order by visits desc) rn
FROM mydataset.mytable
) t1
WHERE rn = 1
ORDER BY customer_key
示例数据:
customer_key store_key store_location visits
111 A A 3
111 C C 3
111 B B 3
111 D D 2
222 D D 5
222 A A 3
222 B B 3
222 C C 3
333 B B 3
333 A A 1
444 C C 4
结果:
考虑以下方法
select as value array_agg(t order by visits desc limit 1)[offset(0)]
from your_table t
group by customer_key
我在 Google BigQuery 中使用 window 函数来获取客户的最大价值,如下所示:
SELECT customer_key, store_location,
FIRST_VALUE(store_key) OVER (
PARTITION BY customer_key
ORDER BY visits DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS fav_store
FROM VISIT_DB
ORDER BY customer_key ASC
它让我的商店有更多的顾客光顾,效果很好。但是,在某些情况下,客户在 3 个不同商店的访问次数相同,并且此函数 return 具有相同的 3 个值。
例如,当顾客 111 在商店 A、B 和 C 有 3 次光顾时,因为它们都有相同的光顾次数,我希望他们中的任何一个都被 returned 而不是全部三个他们。
我也试过用LAST_VALUE
和MAX
但是当访问量相同的时候,他们三个return所有的店。
我怎样才能让它 return 只有一个?
我能够使用此脚本获得预期的输出:
SELECT customer_key, store_location, store_key as fav_store
FROM (
SELECT *, ROW_NUMBER() OVER(partition by customer_key order by visits desc) rn
FROM mydataset.mytable
) t1
WHERE rn = 1
ORDER BY customer_key
示例数据:
customer_key store_key store_location visits
111 A A 3
111 C C 3
111 B B 3
111 D D 2
222 D D 5
222 A A 3
222 B B 3
222 C C 3
333 B B 3
333 A A 1
444 C C 4
结果:
考虑以下方法
select as value array_agg(t order by visits desc limit 1)[offset(0)]
from your_table t
group by customer_key