简体   繁体   中英

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), ie, 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?

I'd group by the ID and filter on two counts:

  1. Total count is 1
  2. Count of rows that aren't type a (using a case statement) is 0


SELECT   id
FROM     t1
GROUP BY id
HAVING   COUNT(*) = 1 AND COUNT(CASE WHEN type <> 'a' THEN 1 END) = 0

You want a simple aggredated query with a HAVING BY clause that ensures that only one row exists and that its type is equal to 'a' .

SELECT id
FROM t1
GROUP BY id
HAVING COUNT(*) = 1 and SUM(DECODE(type, 'a', 0, 1)) = 0

You need id in group by clause & just filter out the type s with having clause:

SELECT id
FROM t1
GROUP BY id
HAVING MIN(type) = MAX(type) AND MIN(type) = 'a';

I would simply do:

SELECT id
FROM t1
GROUP BY id
HAVING COUNT(*) = 1 AND MIN(type) = 'a';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM