0

I have a set of data that resembles the following format.

GROUP | ELEMENT
---------------
  1   |   A
  1   |   B
  1   |   C
  2   |   A
  3   |   B
  4   |   A
  4   |   B
  5   |   A
  5   |   C

I'd like to be able to verify that both elements A AND B exist in each of the groups. Ideally I would return only those groups that have both elements. In the example above I would like to return only GROUP 1 and GROUP 4.

EDIT:
Sorry I should have not implied that 'A' and 'B' were the only options. Is it possible to look specifically for the existence of specific values such as 'A' and 'B'? There may be other possible values. I have updated the example data to reflect this.

4

5 回答 5

3

这是一个更大的Relational Division问题,但您需要GROUP使用每个Element.

询问:

SELECT  a.*
FROM    TableName a
WHERE   EXISTS
        (
            SELECT  1
            FROM    TableName b
            WHERE   a."GROUP" = b."GROUP" AND
                    b."ELEMENT" IN ('A','B')
            GROUP   BY b."GROUP"
            HAVING  COUNT(*) = 2
        )

输出

╔═══════╦═════════╗
║ GROUP ║ ELEMENT ║
╠═══════╬═════════╣
║     1 ║ A       ║
║     1 ║ B       ║
║     1 ║ C       ║
║     4 ║ A       ║
║     4 ║ B       ║
╚═══════╩═════════╝

但是,如果您只想返回GROUP,则可以在下面简单地使用它

SELECT  "GROUP"
FROM    TableName b
WHERE   "ELEMENT" IN ('A','B')
GROUP   BY "GROUP"
HAVING  COUNT(*) = 2

输出

╔═══════╗
║ GROUP ║
╠═══════╣
║     1 ║
║     4 ║
╚═══════╝
于 2013-06-03T16:42:47.197 回答
3

不确定以下是否有效,但您可以尝试一下

SELECT group, COUNT(DISTINCT(element))
FROM table
group by group
having COUNT(DISTINCT(element)) = 2

我不确定是否COUNT(DISTINCT(element))会起作用!

于 2013-06-03T15:32:26.587 回答
1

此查询将返回所有 GROUP(ID)和 ELEMENT(名称),其中每个 GROUP 恰好有 2 个不同的元素。更改HAVING条款以修改“恰好 2 个不同的元素”规则。

SELECT GROUP, ELEMENT 
FROM MyTable
WHERE GROUP in 
    (SELECT GROUP from MyTable
     GROUP BY GROUP 
     HAVING COUNT (DISTINCT ELEMENT)=2
     )
于 2013-06-03T15:38:07.133 回答
0
> SELECT ID,
>        ELEMENT FROM STACK WHERE ID IN
>     (SELECT ID
>      FROM
>        (SELECT id AS ID,
>                COUNT(DISTINCT(element)) AS B
>         FROM STACK
>         WHERE ELEMENT IN ('A',
>                           'B')
>         GROUP BY id HAVING COUNT(DISTINCT(element)) >1)A)   AND ELEMENT IN ('A',
>                   'B');

** id是问题中的 名是stack

如果我们删除“ELEMENT IN”条件,我们将能够获得所有包含多个元素的组

于 2013-06-03T21:39:04.143 回答
0

它返回组只有元素 A 和 B

SELECT a.*
FROM Table a
WHERE EXISTS
(
    SELECT 1
    FROM Table b
    WHERE a.group = b.group
    GROUP BY b.group
   HAVING COUNT(distinct element) = 2
)
and a.element IN ('A','B')
于 2015-06-05T13:36:33.247 回答