0

I have an SQL table:

+-------------+-----------+---------+
|     ID      |  position |  user   |
+-------------+-----------+---------+
|      1      |     1     |     0   |
|      2      |     2     |     0   |
|      3      |     3     |     0   |
|      4      |     4     |     0   |
|      5      |     5     |     0   |
|      6      |     6     |     0   |
|      7      |     7     |     0   |
|      8      |     7     |     1   |
+-------------+-----------+---------+

I would like to filter the duplicate row based on position column and the distinct value of user column, for the first query I need to have the following result:

+-------------+-----------+---------+
|     ID      |  position |  user   |
+-------------+-----------+---------+
|      1      |     1     |     0   |
|      2      |     2     |     0   |
|      3      |     3     |     0   |
|      4      |     4     |     0   |
|      5      |     5     |     0   |
|      6      |     6     |     0   |
|      8      |     7     |     1   |
+-------------+-----------+---------+

For the second query I need the following:

+-------------+-----------+---------+
|     ID      |  position |  user   |
+-------------+-----------+---------+
|      1      |     1     |     0   |
|      2      |     2     |     0   |
|      3      |     3     |     0   |
|      4      |     4     |     0   |
|      5      |     5     |     0   |
|      6      |     6     |     0   |
|      7      |     7     |     0   |
+-------------+-----------+---------+

What queries do I need to achieve this?

Thanks.

1
  • what IF it took another value (2 for example)? in this case what will you need? Commented Jan 23, 2017 at 7:33

1 Answer 1

1

In the absence of further information, the two queries below assume that you want to resolve duplicate positions by taking either the larger (maximum) user value, in the first case, or the smaller (minimum) user value in the second case.

First query:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT position, MAX(user) AS max_user
    FROM yourTable
    GROUP BY position
) t2
    ON t1.position = t2.position AND
       t1.user     = t2.max_user

Second query:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT position, MIN(user) AS min_user
    FROM yourTable
    GROUP BY position
) t2
    ON t1.position = t2.position AND
       t1.user     = t2.min_user
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that's exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.