sql - 解码sql的最大行数

标签 sql postgresql window-functions google-bigquery

我在 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

谢谢

最佳答案

根据您的示例数据,您的排名不稳定,因为您有多行具有相同的键值。在任何情况下,您仍然可以在没有子查询的情况下执行您想要的操作,只需使用 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;

关于sql - 解码sql的最大行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47530329/

相关文章:

postgresql - psycopg 2's "execute()”是否提供足够的 SQL 注入(inject)预防?

mysql - 如何在不检查 SQL 中任何字段的情况下只选择一行一次

mysql - 如何选择列中出现频率最高的 5 个值

sql - ORACLE GROUP BY 错误

postgresql - 用序列表将行乘以列中的数字差

varchar 列上的 MySQL first_value 返回格式错误的记录

mysql - 检索和设置哪个更快?

postgresql - 带文字定界符的 Postgres COPY 命令

sql - 在数据周期内有条件地增加字段值 - 有没有一种仅使用 SQL 的方法?

python - 在 Spark 中应用具有非恒定帧大小的窗口函数