Skip to content
Advertisement

How to retrieve a unique data output using sql query (DISTINCT)?

The data set is like this:

Table A

==type===|| ===score====

Two columns type ands score,

and Table B

==== id ==== || ==== data ====

Two columns as well id and data.

So, the details are as follows:

the id in table B should be an INNER JOIN for the type in table A.

Now an example case of data in each table,

table A:

type == A, score = 75.
type == A, score = 80.   
type == B, score = 65. 
type == B, score = 75.

and table B:

id == A, data = "Good score"
id == B, data = "Not bad..."

I want the query to only select the data that is unique and distinct to it’s own category type i.e. if A it should be score of 80 and not score of 75 as 75 is unique to type B’s score.

Hope that helps with the problem dilemma, and I would appreciate any guidance to this question.

Advertisement

Answer

You can use NOT EXISTS and a correlated subquery to check for the non existence of rows with the same score but different type.

SELECT a1.type,
       a1.score,
       b1.data
       FROM a a1
            INNER JOIN b b1
                       ON b1.id = a1.type
       WHERE NOT EXISTS (SELECT *
                                FROM a a2
                                WHERE a2.score = a1.score
                                      AND a2.type <> a1.type);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement