SQL Server - 如果列包含值,则按 ID 分组

我有下表:

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/

相关文章:

cordova - 内容安全策略 Cordova 问题

python - 阅读 Pandas 数据框时跳过包含特定值的特定行

git - 我需要做一个 Git 克隆吗?

batch-file - 为什么不使用批处理文件中的 RMDIR 作为最后一个命令删除文件夹?

r - 函数不能 "see"全局环境中定义的其他函数

intellij-idea - 使用 Maven 项目创建测试类时,intellij 无法创建类文件

python - 在 Python 中将纳秒转换为时间戳

oop - 开闭原则与多态性

python - 如何在发布数据python中接收字典

r - 使用 R 和 dplyr 扩展和离散化时间序列数据