SQL 一个字段上的 Group by 子句和另一个字段上的特定记录计数条件的帮助
SQL help for Group by clause on one field and specific record count condition on another field
需要帮助获得 SQL。我有以下几种 table.
需要以下结果记录,因为它们在 Field2 中有“abc”和“def”
- 每个值只出现一次而不是更多
- 除了“abc”和“def”之外没有其他值。
预期结果
不应出现在结果中的记录
enter image description here
我用
尝试过不同的实验
Select * from MYTABLE
WHERE FIELD1 in ('abc','def')
Group by Field1
Having Count(*) = 2
但是我在这里做了一些根本性的错误,因为它也给了我“Member4”,因为它出现了两次“abc”
您可以在 having
子句中使用条件聚合表达式:
select field1
from mytable
group by field1
having
sum(case when field2 = 'abc' then 1 else 0 end) = 1
and sum(case when field2 = 'def' then 1 else 0 end) = 1
and sum(case when field2 not in ('abc', 'def') then 1 else 0 end) = 0
大多数数据库都支持字符串聚合。这可能是最简单的方法。例如,在 MySQL 语法中:
select field1
from t
group by field1
having group_concat(field2 order by field2) = 'abc,def';
需要帮助获得 SQL。我有以下几种 table.
需要以下结果记录,因为它们在 Field2 中有“abc”和“def”
- 每个值只出现一次而不是更多
- 除了“abc”和“def”之外没有其他值。
预期结果
不应出现在结果中的记录 enter image description here
我用
尝试过不同的实验Select * from MYTABLE
WHERE FIELD1 in ('abc','def')
Group by Field1
Having Count(*) = 2
但是我在这里做了一些根本性的错误,因为它也给了我“Member4”,因为它出现了两次“abc”
您可以在 having
子句中使用条件聚合表达式:
select field1
from mytable
group by field1
having
sum(case when field2 = 'abc' then 1 else 0 end) = 1
and sum(case when field2 = 'def' then 1 else 0 end) = 1
and sum(case when field2 not in ('abc', 'def') then 1 else 0 end) = 0
大多数数据库都支持字符串聚合。这可能是最简单的方法。例如,在 MySQL 语法中:
select field1
from t
group by field1
having group_concat(field2 order by field2) = 'abc,def';