Ok, I think I might be overlooking something obvious/simple here... but I need to write a query that returns only records that match multiple criteria on the same column...<
Sometimes you can't see the wood for the trees :)
Your original SQL ..
SELECT contactid
WHERE flag = 'Volunteer'
AND flag = 'Uploaded'...
Should be:
SELECT contactid
WHERE flag = 'Volunteer'
OR flag = 'Uploaded'...
your code :
SELECT contactid
WHERE flag = 'Volunteer' AND flag = 'Uploaded' [...]
will not work, for you did not declare the table name. the execution will return an error message.
and if you want both search query to display, your code should look something like this.
SELECT * FROM (your_table_name) WHERE flag = 'Volunteer' OR flag = 'Uploaded';
and not like this because it will always return false SELECT * FROM (your_table_name) WHERE flag = 'Volunteer' AND flag = 'Uploaded';
you can also do this
SELECT * FROM (your_table_name)
WHERE flag = 'Volunteer' OR flag = 'Uploaded'
ORDER BY contactid, flag asc;
(asc for ascending order, you can also change it to desc if you want it to display in descending order)
Change AND to OR. Simple mistake. Think of it like plain English, I want to select anything with that equals this or that.
AND
will return you an answer only when both volunteer
and uploaded
are present in your column. Otherwise it will return null
value...
try using OR
in your statement ...
SELECT contactid WHERE flag = 'Volunteer' OR flag = 'Uploaded'
SELECT contactid, Count(*)
FROM <YOUR_TABLE> WHERE flag in ('Volunteer','Uploaded')
GROUP BY contactid
HAVING count(*)>1;
Use:
SELECT t.contactid
FROM YOUR_TABLE t
WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
HAVING COUNT(DISTINCT t.flag) = 2
The key thing is that the counting of t.flag
needs to equal the number of arguments in the IN
clause.
The use of COUNT(DISTINCT t.flag)
is in case there isn't a unique constraint on the combination of contactid and flag -- if there's no chance of duplicates you can omit the DISTINCT from the query:
SELECT t.contactid
FROM YOUR_TABLE t
WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
HAVING COUNT(t.flag) = 2