SQL:如何基于两个字段查找重复项? [英] SQL: How to find duplicates based on two fields?

查看:625
本文介绍了SQL:如何基于两个字段查找重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Oracle数据库表中有一些行,这两个字段的组合应该是唯一的,但是表上没有设置唯一的约束,因此我需要使用SQL查找所有违反约束的行.不幸的是,我微不足道的SQL技能不能胜任这项工作.

I have rows in an Oracle database table which should be unique for a combination of two fields but the unique constrain is not set up on the table so I need to find all rows which violate the constraint myself using SQL. Unfortunately my meager SQL skills aren't up to the task.

我的表有三列相关:entity_id,station_id和obs_year.对于每一行,station_id和obs_year的组合应该是唯一的,我想通过使用SQL查询将它们刷新来找出是否存在违反此规定的行.

My table has three columns which are relevant: entity_id, station_id, and obs_year. For each row the combination of station_id and obs_year should be unique, and I want to find out if there are rows which violate this by flushing them out with an SQL query.

我尝试了以下SQL(由此先前的问题建议)但这对我不起作用(我得到了ORA-00918列的定义不明确):

I have tried the following SQL (suggested by this previous question) but it doesn't work for me (I get ORA-00918 column ambiguously defined):

SELECT
entity_id, station_id, obs_year
FROM
mytable t1
INNER JOIN (
SELECT entity_id, station_id, obs_year FROM mytable 
GROUP BY entity_id, station_id, obs_year HAVING COUNT(*) > 1) dupes 
ON 
t1.station_id = dupes.station_id AND
t1.obs_year = dupes.obs_year

有人可以建议我做错了什么,和/或如何解决这个问题?

Can someone suggest what I'm doing wrong, and/or how to solve this?

推荐答案

SELECT  *
FROM    (
        SELECT  t.*, ROW_NUMBER() OVER (PARTITION BY station_id, obs_year ORDER BY entity_id) AS rn
        FROM    mytable t
        )
WHERE   rn > 1

这篇关于SQL:如何基于两个字段查找重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆