I have a table called Survey with a Group Column and a Subject Column
CREATE TABLE survey (
`group` INT NOT NULL,
`subject` VARCHAR(16) NOT NULL,
UNIQUE INDEX (`group`, `subject`)
);
INSERT INTO survey
VALUES
(1, 'sports'),
(1, 'history'),
(2, 'art'),
(2, 'music'),
(3, 'math'),
(3, 'sports'),
(3, 'science')
;
I am trying to figure out a query that will return all pairs of subjects that are not part of the same group. So from my above example, I would like to see these pairs returned in a table:
science - history
science - art
science - music
history - math
sports - art
sports - music
history - art
history - music
Thus, the query shouldn't return:
sports - history
as an example since they are both in Group 1.
Thanks so much.
SELECT s1.subject,
s2.subject
FROM survey s1
JOIN survey s2
ON s1.subject < s2.subject
GROUP BY s1.subject,
s2.subject
HAVING COUNT(CASE
WHEN s1.groupid = s2.groupid THEN 1
END) = 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With