问题
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:
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
来源:https://stackoverflow.com/questions/41800911/sql-filter-duplicate-rows-based-on-a-value-in-a-different-column