将多个变量都视为“两个”的SQL函数

时间:2019-06-12 15:28:50

标签: sql function classification

在这种情况下,有两列。

  • A列=案例ID(记录的唯一ID)
  • B列=性别可能是男性,女性

注意事项 如果一个案例ID与多个性别相关联,则可以有多个记录。

示例数据集:

ColumnA  ColumnB
Case001  Male        
Case001  Female 
Case002  Male 
Case003  Female 
data set continues... 

问题:我想将结果分类为Case001,其中两个结果均为“两个”。最佳解决方案是什么?有没有公​​式或标准的方法可以做到这一点?

所需的样本数据集:

ColumnA  ColumnB
Case001  Both           
Case002  Male 
Case003  Female 
data set continues... 

谢谢!

我可以用case语句和子查询来完成。但是,我希望有一个更好的解决方案。

3 个答案:

答案 0 :(得分:0)

使用聚合和case表达式:

select col1,
       (case when min(gender) = max(gender) then min(gender)
             else 'both'
        end) as gender
from cases c
group by col1;

答案 1 :(得分:0)

您可以在CASE语句中使用EXISTS:

select distinct
  t.ColumnA,
  case 
    when exists (
      select 1 from tablename
      where ColumnA = t.ColumnA and ColumnB <> t.ColumnB
    ) then 'Both'
    else t.ColumnB
  end
from tablename t

答案 2 :(得分:0)

group byhaving子句结合union all如下所示可能是一个不错的选择:

with t( ColumnA, ColumnB ) as
(
 select 'Case001', 'Male'   union all
 select 'Case001', 'Female' union all
 select 'Case002', 'Male'   union all
 select 'Case003', 'Female'    
)    
select ColumnA, 'Both' ColumnB from t group by ColumnA having count(distinct ColumnB) = 2
union all
select ColumnA, max(ColumnB)   from t group by ColumnA having count(distinct ColumnB) = 1;

ColumnA ColumnB
------- -------
Case001 Both
Case002 Male
Case003 Female

从那时起,只有两种或两种性别可能出现,

Demo