返回具有相同 ID 但在第二列中排除某些行的行
Returning rows with the same ID but exclude some on second column
我看到过类似的问题,但不是很切合我的需要。假设我有一个 table.
+-----+-------+
| ID | Value |
+-----+-------+
| 123 | 1 |
| 123 | 2 |
| 123 | 3 |
| 456 | 1 |
| 456 | 2 |
| 456 | 4 |
| 789 | 1 |
| 789 | 2 |
+-----+-------+
我想 return 不同的 ID,但排除具有特定值的 ID。例如,假设我不想要任何具有 3 作为值的 ID。我的结果应该是这样的。
+-----+
| ID |
+-----+
| 456 |
| 789 |
+-----+
我希望这是有道理的。如果需要更多信息,请询问,如果之前已经回答过,请指出正确的方向。谢谢
您可以使用 group by
和 having
:
select id
from t
group by id
having sum(case when value = 3 then 1 else 0 end) = 0;
having
子句计算“3"s for each id. The = 0
returns only returns groups where the count is 0 (i.e. there are no "3”的个数。
您可以使用 not exists
:
select distinct t.id
from table t
where not exists (select 1 from table t1 where t1.id = t.id and t1.value = 3);
试试这个:
select id from tablename
group by id
having (case when value=3 then 1 else 0 end)=0
您还可以使用 EXCEPT 比较以下两个数据集,它们将给出所需的结果集
select distinct Id from ValuesTbl
except
select Id from ValuesTbl where Value = 3
我看到过类似的问题,但不是很切合我的需要。假设我有一个 table.
+-----+-------+
| ID | Value |
+-----+-------+
| 123 | 1 |
| 123 | 2 |
| 123 | 3 |
| 456 | 1 |
| 456 | 2 |
| 456 | 4 |
| 789 | 1 |
| 789 | 2 |
+-----+-------+
我想 return 不同的 ID,但排除具有特定值的 ID。例如,假设我不想要任何具有 3 作为值的 ID。我的结果应该是这样的。
+-----+
| ID |
+-----+
| 456 |
| 789 |
+-----+
我希望这是有道理的。如果需要更多信息,请询问,如果之前已经回答过,请指出正确的方向。谢谢
您可以使用 group by
和 having
:
select id
from t
group by id
having sum(case when value = 3 then 1 else 0 end) = 0;
having
子句计算“3"s for each id. The = 0
returns only returns groups where the count is 0 (i.e. there are no "3”的个数。
您可以使用 not exists
:
select distinct t.id
from table t
where not exists (select 1 from table t1 where t1.id = t.id and t1.value = 3);
试试这个:
select id from tablename
group by id
having (case when value=3 then 1 else 0 end)=0
您还可以使用 EXCEPT 比较以下两个数据集,它们将给出所需的结果集
select distinct Id from ValuesTbl
except
select Id from ValuesTbl where Value = 3