【问题标题】:Output 1 if count(*) is greater than 0. output 0 otherwise如果 count(*) 大于 0,则输出 1。否则输出 0
【发布时间】:2021-09-27 14:01:13
【问题描述】:

我有一张如下所示的表格:

+--------------+----------------+
| PersonColumn | AttendedColumn |
+ ------------ + -------------- +
| person1      | attended       |
| person1      | not attended   |
| person2      | not attended   |
| person2      | not attended   |
| person2      | not attended   |
| person3      | attended       |
| person3      | attended       |
+--------------+----------------+

所以我想要一个 select 语句来输出这个:

+---------+-----+
| person1 |  1  |
| person2 |  0  |
| person3 |  1  |
+---------+-----+

也就是说,如果该人至少参加过一次,则输出 1。否则输出零。我正在使用 ORACLE

【问题讨论】:

    标签: sql oracle oracle11g


    【解决方案1】:
    Select personcolumn, max(decode(attendedcolumn,'attended',1,0)) from ... group by personcolumn
    

    【讨论】:

    • 这很聪明,很简短。
    【解决方案2】:

    您可以使用CASEGROUP BY 使用条件聚合。

    例如:

    select
      personcolumn,
      case when 
        sum(case when attendedcolumn = 'attended' then 1 else 0 end) > 0
        then 1
        else 0 
      end as attended
    from t
    group by personcolumn
    

    结果:

     PERSONCOLUMN  ATTENDED 
     ------------- -------- 
     person1       1        
     person2       0        
     person3       1        
    

    请参阅db<>fiddle 的运行示例。

    【讨论】:

    • case 表达式可以缩短为sign(count(case ...))
    【解决方案3】:

    你可以使用简单的max():

    select personcolumn,
           max(case when attendedcolumn = 'attended' then 1 else 0 end) 
    from t
    group by personcolumn;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 2021-07-24
      相关资源
      最近更新 更多