Given the following table:
Column1 | Column2
10 | 200
10 | 201
11 | 100
11 | 200
11 | 300
12 | 200
13 | 100
13 | 200
13 | 201
13 | 300
I wish to extract all rows where column2 contains the value 200 and 201 for each unique column1. The output should be:
10 | 200
10 | 201
13 | 200
13 | 201
The table contains about 8 million rows and all the things I can come up with are rather slow.
Do it with:
SELECT
t.*
FROM
t
INNER JOIN
(SELECT
Column1
FROM
t
WHERE
Column2 IN (200,201)
GROUP BY
Column1
HAVING
COUNT(DISTINCT Column2)>1) AS c
ON t.Column1=c.Column1
-but note, this will output rows with all Column2
values (ie not only 200
and 201
) if it's not an intention, filter them:
SELECT
t.*
FROM
t
INNER JOIN
(SELECT
Column1
FROM
t
WHERE
Column2 IN (200,201)
GROUP BY
Column1
HAVING
COUNT(DISTINCT Column2)>1) AS c
ON t.Column1=c.Column1
WHERE
Column2 IN (200,201)
fiddle is available here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.