如果Account_ID 存在一些account_type,则使用解析函数计算标志。
例如这个解析函数
max(case when Account_type='First' then 1 else 0 end) over(partition by account_id) first_exists_flag
对于数据集中的所有 account_id=101 记录和 0 将是 1。希望你明白了。
当 First 不存在时选择 Second account_type:
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;
当 First 和 Second 不存在时选择 Third account_type:
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过滤