我在bigquery中使用#standardsql
并尝试将每个customer_id的最高排名编码为1
,其余部分为0
这是到目前为止的查询结果
排名查询是
ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY booking_date Asc) as ranking
我需要创建另一个这样的列,它将每个customerid
的最大排名解码为1,将其下面的数字解码为0
,如下表所示
由于
答案 0 :(得分:1)
我们可以打包您当前的查询,然后使用MAX
作为分析函数,并按客户分区将每个ranking
值与每个客户的最大ranking
进行比较。当ranking
值等于客户的最大值时,我们为custom_coded
分配1,否则我们分配0。
SELECT
customer_id, item_bought, booking_date, ranking,
CASE WHEN ranking = MAX(ranking) OVER (PARTITION BY customer_id)
THEN 1 ELSE 0 END AS custom_coded
FROM
(
SELECT customer_id, item_bought, booking_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY booking_date) ranking
FROM yourTable
) t;
答案 1 :(得分:1)
根据您的示例数据,您的排名不稳定,因为您有多个具有相同键值的行。在任何情况下,只需使用case
:
select t.*,
row_number() over (partition by customer_id order by booking_date asc) as ranking,
(case when row_number() over (partition by customer_id order by booking_date asc) =
count(*) over (partition by customer_id)
then 1 else 0
end) as custom_coded
from t;
一种更传统的做同样事情的方法是使用降序排序:
select t.*,
row_number() over (partition by customer_id order by booking_date asc) as ranking,
(case when row_number() over (partition by customer_id order by booking_date desc) = 1
then 1 else 0
end) as custom_coded
from t;