在一组行中查找非数字值

问题描述 投票:0回答:3

我需要组值并根据组中的值分配状态。示例:

客户 购买 状态
客户1 购买 1 状态1
客户1 购买2 状态2
客户1 购买3 状态1
客户2 购买4个 状态2
客户2 购买5个 状态3
客户端3 购买4个 状态1
客户端3 购买5个 状态4

按客户端分组并分配状态 IF 组中状态 1 THEN 客户端状态 = 状态 1 ELSEIF 组中状态 2 THEN 客户端状态 = 状态 2 等等。

预期结果:

客户 主要状态
客户1 状态1
客户2 状态2
客户端3 状态1

状态 1 具有最高优先级,状态 4 - 最低优先级。

sql google-bigquery
3个回答
0
投票

参见示例

select * 
from(
  select *
    ,row_number()over(partition by Client order by StatusOrder) rnk
  from(
    select *
     ,case when Status='Status 1' then 1
           when Status='Status 2' then 2
           when Status='Status 3' then 3
           when Status='Status 4' then 4
      else null
      end StatusOrder
    from test
   )x
 )y
where rnk=1

输出

客户 购买 状态 状态订单 rnk
客户1 购买3 状态1 1 1
客户2 购买4个 状态2 2 1
客户端3 购买4个 状态1 1 1

0
投票

使用以下方法

SELECT Client, Statuses[Main_Status_Index - 1] AS Main_Status
FROM (
  SELECT Client, 
    ANY_VALUE(Statuses) AS Statuses, 
    MIN(RANGE_BUCKET(Status, Statuses)) AS Main_Status_Index
  FROM your_table, 
  UNNEST([STRUCT(['Status 1', 'Status 2', 'Status 3', 'Status 4'] AS Statuses)])
  GROUP BY Client
)

如果应用于问题中的样本数据 - 输出是


0
投票

根据第一个表,假设 T1:

SELECT client, SUBSTR (StatusGroup, 1, INSTR (StatusGroup, '-') - 1) "Main Status"
  FROM (  SELECT client,
                 LISTAGG (status, '-')
                 WITHIN GROUP (ORDER BY
                                   DECODE (status,
                                           'Status 1', 1,
                                           'Status 2', 2,
                                           'Status 3', 3,
                                           4))    StatusGroup
            FROM T1
        GROUP BY client)
© www.soinside.com 2019 - 2024. All rights reserved.