为sql解码行的最大数量

时间:2017-11-28 11:22:16

标签: sql postgresql google-bigquery window-functions standard-sql

我在bigquery中使用#standardsql并尝试将每个customer_id的最高排名编码为1,其余部分为0

这是到目前为止的查询结果

rankings customer_id

排名查询是

ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY booking_date Asc) as ranking

我需要创建另一个这样的列,它将每个customerid的最大排名解码为1,将其下面的数字解码为0,如下表所示

enter image description here

由于

2 个答案:

答案 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;