sql—当配置单元中不存在其他帐户时选择一个帐户

q3aa0525  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(362)

当配置单元中不存在其他帐户类型时,我要选择帐户
我用 Account_type = 'Second' ,但所有的记录都来了

Select Account_ID, Account_type
From Account
Where Account_type = 'Second'

我的预期结果是:

Account_ID  Account_type

102         Second

实际结果是

Account_ID  Account_type

101         Second 
102         Second

aemubtdh

aemubtdh1#

使用解析函数来计算 account_type 存在于 Account_ID .
例如这个解析函数

max(case when Account_type='First'  then 1 else 0 end) over(partition by account_id) first_exists_flag

1 对所有人 account_id=101 记录和 0 对于数据集中的所有其他记录。希望你有这个想法。
当第一个帐户不存在时,选择第二个帐户类型:

with account as (
    select a.*, 
              max(case when Account_type='First'  then 1 else 0 end) over(partition by account_id) first_exists_flag,
              max(case when Account_type='Second' then 1 else 0 end) over(partition by account_id) second_exists_flag
              --you can add more such flags
          from Account a
)

select account_id, account_type
  from account a
where a.account_type='Second' and first_exists_flag=0;

当第一个和第二个帐户不存在时,选择第三个帐户类型:

with account as (
    select a.*, 
              max(case when Account_type='First'  then 1 else 0 end) over(partition by account_id) first_exists_flag,
              max(case when Account_type='Second' then 1 else 0 end) over(partition by account_id) second_exists_flag
              --you can add more such flags
          from Account a
)

select account_id, account_type
  from account a
where a.account_type='Third' and first_exists_flag=0 and second_exists_flag=0;

当存在第三方账户类型以外的其他账户类型时,您还可以计算标志:

max(case when Account_type <> 'Third'  then 1 else 0 end) over(partition by account_id) other_account_exist_flag

并使用 other_account_exist_flag=0

相关问题