farm ostrich
farm ostrich

Reputation: 5989

MySQL distinct values query

I need help with a relatively simple query. For a table:

A | B | C 
----------
2   1   6
2   2   5
3   3   4
4   4   3
5   5   2
6   6   1

I need to have an output like so:

A | B | C 
----------
2   1   6
3   3   4
4   4   3
5   5   2
6   6   1

So that each value in A is distinct, but I also get the corresponding values in B and C. I know "select distinct(A) from table" but that only returns the values 2,3,4,5,6 and I need the values in columns B and C, too. Please help. I have a deadline fast approaching. This question is stupid and trivial, but one must walk before they can run. Thanks so much.

Upvotes: 2

Views: 2245

Answers (2)

Mark Byers
Mark Byers

Reputation: 839044

Try this:

SELECT T1.A, T1.B, MIN(T1.C) AS C
FROM yourtable T1
JOIN (
    SELECT A, MIN(B) AS B
    FROM yourtable
    GROUP BY A
) T2
ON T1.A = T2.A AND T1.B = T2.B
GROUP BY T1.A, T1.B

Upvotes: 1

Tyler Ferraro
Tyler Ferraro

Reputation: 3772

SELECT DISTINCT(A), B, C
FROM table

Is there a specific logic behind which distinct A rows you want to select when considering columns B and C?

Upvotes: 1

Related Questions