Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Selecting unique values from one column then filtering based on another

Tags:

sql

I've had a search around and have seen quite a few questions about selecting distinct values, but none of them seem close enough to my query to be able to help. This is the scenario

ID   Product_ID   Product_type
123  56789        A
123  78901        B
456  12345        A
789  45612        B

The SQL I need would be to search in a table similar to the above, and bring back the rows where the Product_type is B but only if the ID related to it exists once within the table.

So in this case it would bring back only

789  45612        B

The SQL I have tried based on what I've found so far was

SELECT DISTINCT(ID)
FROM "TABLE"
WHERE "PRODUCT_TYPE" = 'B'

As well as

SELECT *                        
FROM   "TABLE"
WHERE  "PRODUCT_TYPE" = 'B'       
GROUP BY "ID"              
HAVING COUNT(ID) = 1 

And neither have worked

like image 820
Jsmith2800 Avatar asked Oct 28 '25 03:10

Jsmith2800


1 Answers

One way via a list of IDs appearing once:

select * from T where Product_type = 'B' and id in (
select id from T
    group by id
    having count(id) = 1)
like image 119
Alex K. Avatar answered Oct 29 '25 17:10

Alex K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!