Sql 在oracle中查找重复值
我使用此查询查找表中的重复值:Sql 在oracle中查找重复值,sql,oracle,Sql,Oracle,我使用此查询查找表中的重复值: select col1, count(col1) from table1 group by col1 having count (col1) > 1 order by 2 desc; 但我还想从同一个表中添加另一列,如下所示: select col1, col2, count(col1) from table1 group by col1 having count (col1) &
select col1,
count(col1)
from table1
group by col1
having count (col1) > 1
order by 2 desc;
但我还想从同一个表中添加另一列,如下所示:
select col1,
col2,
count(col1)
from table1
group by col1
having count (col1) > 1
order by 2 desc;
Col1 | Col2
-----+-----
1 | A
1 | B
2 | C
2 | D
3 | E
我在第二次查询中得到一个ORA-00979
错误
如何在搜索中添加其他列 您还应该列出GROUPBY子句中的所有选定列
select col1,
col2,
count(col1)
from table1
group by col1, col2
having count (col1) > 1
order by 2 desc;
错误原因 您试图执行包含GROUP BY的SQL SELECT语句 函数(即:SQL最小函数、SQL最大函数、SQL求和函数、, SQL计数函数)和选择列表中未指定的表达式 在SQL GROUPBY子句中 您的查询应该是
SELECT * FROM (
select col1,
col2,
count(col1) over (partition by col1) col1_cnt
from table1
)
WHERE col1_cnt > 1
order by 2 desc;
大概您希望为出现的每个
col1
副本获取col2
。你不可能在一个查询中做到这一点。相反,您需要做的是获取副本列表,然后使用该列表检索任何其他关联值:
select col1, col2
from table1
where col1 in (select col1
from table1
group by col1
having count (col1) > 1)
order by col2 desc
^好的,你可以,通过使用解析函数,如@rs.所示。对于这种情况,我怀疑嵌套查询会更有效,但两者都会给出相同的结果
根据评论,您似乎不清楚为什么不能只添加第二列。假设您有如下示例数据:
select col1,
col2,
count(col1)
from table1
group by col1
having count (col1) > 1
order by 2 desc;
Col1 | Col2
-----+-----
1 | A
1 | B
2 | C
2 | D
3 | E
如果你跑
select Col1, count(*) as cnt
from table1
group by Col1
having count(*) > 1
那么您的结果将是:
Col1 | Cnt
-----+-----
1 | 2
2 | 2
您不能只将Col2
添加到此查询,而不将其添加到group by
子句中,因为数据库无法知道您实际需要哪个值(即,对于Col1=1,数据库是否应返回“A”或“B”)。如果将Col2添加到group by
子句中,则会得到以下结果:
select Col1, Col2, count(*) as cnt
from table1
group by Col1, Col2
having count(*) > 1
Col1 | Col2 | Cnt
-----+------+----
[no results]
这是因为计数是针对Col1
和Col2
的每个组合(每个组合都是唯一的)
最后,通过使用嵌套查询(如我的答案)或分析函数(如@rs.的答案),您将得到以下结果(查询稍微更改以返回计数):
将第二列添加到您的组:COL1、COL2组,或者您可以选择一个max(COL2)。是否要查找
col1
和col2
组合重复的情况?或者您只是想从第一次查询中获取数据和逻辑并返回一列额外的参考数据?@JustinCave否,我只是想知道表中有多少次col1的值,col2只是记录的id。@AleksanderBlomskøld的可能重复项类似但不相同,请阅读我的问题,我想在我的查询列表中添加另一列,它可以工作,但我得到了重复的行,无论如何,谢谢