this is a follow on question to a previously asked question.
I have the following data in a single db table.
Name LeftId RightId
------------------------------------------
Cat 1
Cat 1
Dog 2
Dog 2
Dog 3
Dog 3
Gerbil 4 5
Cat
Bird
Cow 6
Cow
Cow 7
Dog 8 9
Note that some rows have NO data for for LeftId and RightId.
Now, what i wish to do is find two different queries
- All rows which have at least 1 Id in one of the two columns AND row with NO data in both of those two Id columns.
eg.
Cat 1
Cow 6 (or 7 .. i'm not worried)
- All the rows where LeftId and RightId are NULL grouped by the same name. If another row (with the same name) has a value in the LeftId or RightId, this this name will not be returned.
eg.
Bird
hmm..
EDIT: Reworded the first question properly.
For the first query, you want rows that answer to both of the following criteria:
Namein the row appears in the table in the same row in whichLeftIdandRightIdare both NULL.Namein the row appears in the table in same row where at at least one ofLeftIdandRightIdis not NULL.Well, #1 is done by:
And #2 is done by:
You could intersect them to see which
Names appear in both lists:Which returns:
But you want the
LeftIdandRightId, and you don’t care which, so I guess we’ll aggregate on the Name:Which returns
lc already suggested using COALESE to turn those two IDs to a single one. So how about this:
Which returns:
For the second query, you want rows that obey the following criteria:
Nameappears only in rows that have noLeftIdandRightIdI can’t think of a way to do that sort of self-referencing query in SQL in a single set of criteria, so I’ll break it down to two criteria. Both must be obeyed to be acceptable:
Nameappears in rows that have noLeftIdandRightIdNamedoes not appear in rows that have eitherLeftIdorRightIdDoing #1 is simply:
But #2 is tricky. Of course doing the opposite of #2 (“all the
Namethat appear in rows that have eitherLeftIdorRightId) is just like before:Now comes the tricky bit – we want all the rows that obey #1 but don’t obey the opposite of #2. This is where EXCEPT is useful:
Which returns:
Which is what we wanted!