Input table has following data:
+--------+-----+
| Id | set |
+--------+-----+
| ABC123 | 1 |
| ABC123 | 0 |
| ABC123 | 1 |
| XYZ123 | 0 |
| XYZ123 | 0 |
| XYZ123 | 0 |
| ZAC123 | 1 |
| ZAC123 | 0 |
| TNB123 | 0 |
| TNB123 | 0 |
| TNB123 | 0 |
| BBB123 | 1 |
| BBB123 | 0 |
| BBB123 | 1 |
| BBB123 | 1 |
+--------+-----+
Need result as below:
+--------+-----+
| Id | set |
+--------+-----+
| XYZ123 | 0 |
| XYZ123 | 0 |
| XYZ123 | 0 |
| TNB123 | 0 |
| TNB123 | 0 |
| TNB123 | 0 |
+--------+-----+
Query
Select *
from X
where set='0'
having count(*)>1
Not working as some are only one record as well
5
Answers
This is one way:
This will select all
id
s where set is not 0 in a subquery, then filter out those rows with anot in
over the whole table.https://dbfiddle.uk/QCPgxcK7 (Thanks @xQbert for the setup code)
sergey was close:
The issue here is you need to return all records and a group by given duplicate values will eliminate those. So we need to first get a set of data which is for records where the set is all 0’s and has a count > 1 then query the base set (x) for those records; returning all of them.
DEMO
May not need the having count(*)>1 if you want records id’s which only have 1 record with a set of 0.
Giving us:
Use
SUM()
window function to sum all set values for each Id. Return the Id’s where that sum is equal to 0.Demo: https://dbfiddle.uk/iIw7_VHz (Built on @Dogbert’s, thanks!)
Note: If set can be negative, do
Two other ways :