我有下表:
ID | NR | Status
1000 | 1 | A
1000 | 2 | A
1001 | 3 | A
1002 | 4 | A
1002 | 5 | N
1003 | 6 | N
我需要一个按ID
对这些进行分组的输出。 NR
列可以忽略。如果具有这些 ID 的
的记录之一包含状态 A,则该 status
将作为结果给出。
所以我的输出是:
ID | Status
1000 | A
1001 | A
1002 | A
1003 | N
有什么建议/想法吗?
最佳答案
尽管 min()
是最简单的方法,但它不容易推广。另一种方法是:
select id
(case when sum(case when status = 'A' then 1 else 0 end) > 0
then 'A'
else 'N' -- or whatever
end) as status
from t
group by id;
或者,如果您有一个表,每个 id
一行,那么我会使用 exists
:
select ids.id,
(case when exists (select 1 from t where t.id = ids.id and t.status = 'A')
then 'A' else 'N'
end) as status
from ids;
这节省了 group by
聚合,并且可以在 (id, status)
上使用索引以获得最佳性能。
https://stackoverflow.com/questions/40592130/