简体   繁体   English

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

[英]SQL Server - group by ID if column contains a value

I have following table: 我有下表:

ID   | NR | Status
1000 | 1  | A
1000 | 2  | A
1001 | 3  | A
1002 | 4  | A
1002 | 5  | N
1003 | 6  | N

I need to an output which groups these by ID's . 我需要一个按ID's这些分组的输出。 The NR column can be ignored. NR列可以忽略。 If one of the records with those ID's contains Status A, That status will be given as result. 如果具有这些ID's记录之一包含状态A,则将给出该status作为结果。

So my output would be: 所以我的输出是:

ID   | Status
1000 | A 
1001 | A 
1002 | A 
1003 | N 

Any suggestions/ideas? 有什么建议/想法吗?

Do a GROUP BY , use MIN() to pick minimum status value for each id, and A < N! 执行GROUP BY ,使用MIN()为每个id选择最小状态值,并且A <N!

select id, min(status)
from tablename
group by id

Although min() is the simplest method, it is not easily generalizable. 尽管min()是最简单的方法,但不容易推广。 Another method is: 另一种方法是:

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;

Or, if you have a table with one row per id , then I would use exists : 或者,如果您有一个表,每个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;

This saves on the group by aggregation and can use an index on (id, status) for optimal performance. 这样可以group by聚合节省group by并且可以使用索引(id, status)以获得最佳性能。

You want exactly the records that match the predicate "If one of the records with those ID's contains Status A, that status will be given as result." 您需要与谓词完全匹配的记录:“如果具有这些ID的记录之一包含状态A,则该状态将作为结果给出。” ? The query can be written simply as: 该查询可以简单地写为:

Select distinct ID, STATUS from [your working TABLE] where STATUS = 'A'.

Hope this can help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM