解码 sql 的最大行数
Decode maximum number in rows for sql
我在 bigquery 中使用 #standardsql
并尝试将每个 customer_id 的最大排名编码为 1
,其余为 0
这是目前的查询结果
排名查询是这个
ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY booking_date Asc) as ranking
我需要创建另一个像这样的列,它将每个 customerid
的最大排名解码为 1,将其下方的数字解码为 0
,就像下面的 table
谢谢
我们可以包装您当前的查询,然后将 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;
根据您的示例数据,您的排名不稳定,因为您有多行具有相同的键值。在任何情况下,你仍然可以在没有子查询的情况下做你想做的,只需使用 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;
我在 bigquery 中使用 #standardsql
并尝试将每个 customer_id 的最大排名编码为 1
,其余为 0
这是目前的查询结果
排名查询是这个
ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY booking_date Asc) as ranking
我需要创建另一个像这样的列,它将每个 customerid
的最大排名解码为 1,将其下方的数字解码为 0
,就像下面的 table
谢谢
我们可以包装您当前的查询,然后将 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;
根据您的示例数据,您的排名不稳定,因为您有多行具有相同的键值。在任何情况下,你仍然可以在没有子查询的情况下做你想做的,只需使用 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;