SQL - filter duplicate rows based on a value in a different column

社会主义新天地 提交于 2019-12-10 12:14:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!