如果 count(*) 大于 0,则输出 1。否则输出 0
Output 1 if count(*) is greater than 0. output 0 otherwise
我有一个 table 看起来像这样:
+--------------+----------------+
| 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
您可以使用 CASE
和 GROUP 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 中的 运行 示例。
Select personcolumn, max(decode(attendedcolumn,'attended',1,0)) from ... group by personcolumn
您可以使用简单的 max()
:
select personcolumn,
max(case when attendedcolumn = 'attended' then 1 else 0 end)
from t
group by personcolumn;
我有一个 table 看起来像这样:
+--------------+----------------+
| 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
您可以使用 CASE
和 GROUP 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 中的 运行 示例。
Select personcolumn, max(decode(attendedcolumn,'attended',1,0)) from ... group by personcolumn
您可以使用简单的 max()
:
select personcolumn,
max(case when attendedcolumn = 'attended' then 1 else 0 end)
from t
group by personcolumn;