简体   繁体   English

选择特定ID的行,其中与之对应的列仅提及一组值

[英]Selecting Rows for a particular ID where columns corresponding to that have only mentioned set of values

I have a table as follows: 我有一张桌子,如下所示:

ID  | Value  | Other Columns...........| .......
-----------------------------------------------
ID1 | Value1 | ....................... | .......
ID1 | Value2 | ....................... | .......
ID2 | Value3 | ....................... | .......
ID3 | Value4 | ....................... | .......
ID3 | Value4 | ....................... | .......
ID3 | Value5 | ....................... | .......
ID4 | Value4 | ....................... | .......
ID4 | Value5 | ....................... | .......
ID5 | Value2 | ....................... | .......
ID5 | Value4 | ....................... | .......
ID5 | Value5 | ....................... | .......

The Value column can have 5 types of values : Value1 through Value5. “值”列可以具有5种类型的值:“值1”到“值5”。 I need to write a query where I should get all IDs where Values are only Value4 and Value5 . 我需要编写一个查询,在其中我应该获取所有ID均为Value4Value5的ID Example: ID3 and ID4 . 示例: ID3ID4 As I am new to SQL, how should I go about it in an optimized way? 当我刚接触SQL时,应该如何以优化的方式进行处理?

You can use group by and having . 您可以使用group byhaving A simple way is: 一种简单的方法是:

select id
from t
group by id
having sum(case when value = 'value4' then 1 else 0 end) > 0 and
       sum(case when value = 'value5' then 1 else 0 end) > 0 and
       sum(case when value not in ('value4', 'value5') then 1 else 0 end) = 0;

The conditions are counting how many times the value is each of the values for a given id . 条件是计算给定idvalue是每个value多少次。 The > 0 says that at least one row has the value. > 0表示至少有一行具有该值。 The = 0 says that no rows with the id have the value. = 0表示没有id行具有该值。

我只是给您一个关于查询的粗略想法。

Select * from table where value is value or value 4

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

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