Skip to content
Advertisement

Oracle SQL: How to write below SQL in Oracle

There is a table t1:

id type 
1    a
1    b
2    c
2    a
3    a
3    a
4    a

Now I need to check if the id only has type a and the count is 1 (single), i.e., only id 4 satisfies this condition in the data above

SELECT type, COUNT (1)
FROM t1
where id = :id
GROUP BY type
HAVING COUNT (1) = 1;

I use the above SQL query to get the data and then use it in code. It’s not a good solution, can anyone help me to get the correct result with one SQL query?

Advertisement

Answer

I would simply do:

SELECT id
FROM t1
GROUP BY id
HAVING COUNT(*) = 1 AND MIN(type) = 'a';
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement