简体   繁体   English

SQL:提取某些条件下的记录

[英]Sql: Extract records with some condition

I have rows in Oracle database table (having +2M records) and I want to extract records with some condition. 我在Oracle数据库表中有行(具有+ 2M条记录),并且我希望在某些情况下提取记录。 The constraint is not setup on the table. 没有在表上设置约束。 Any help will be appreciated. 任何帮助将不胜感激。

nif                 num_sum
--------------------------
123                   456
123                   456
123                   789   // => I want to select this
134                   600

Records having a nif with one or more same num_sum is allowed. 允许具有一个具有一个或多个相同num_sumnif记录。 But if a nif exists for two or more different num_sum s, I want to select that nif and num_sum . 但是,如果一个nif存在两个或多个不同num_sum S,我想选择nifnum_sum I showed the above records for explanation only. 我显示以上记录仅供参考。

I tried: 我试过了:

select distinct nif, num_sum
from sumcon
group by nif, num_sum
having count(distinct nif) > 1 

您不返回任何记录,因为nif只有1个不同的值,因此计数不大于1。

Given your description, 根据您的描述,

"Records having a nif with one or more same num_sum is allowed (a nif shouldn't be for two different num_sums)" “允许记录具有一个或多个相同num_sum的nif(一个nif不应用于两个不同的num_sum)”

I think you want the following: 我认为您需要以下条件:

SELECT nif
  FROM sumcon
 GROUP BY nif
HAVING COUNT(DISTINCT num_sum) > 1;

First, in your original query DISTINCT is superfluous. 首先,在原始查询中DISTINCT是多余的。 Next, since you say there should not exist more than one distinct value of num_sum for a given value of nif , I think you want to group by nif and use COUNT(DISTINCT num_sum) . 接下来,由于您说对于给定的nif值,不应该存在多个不同的num_sum值,因此我认为您希望按nif分组并使用COUNT(DISTINCT num_sum) Now if you mean that a given value of num_sum should not exist for more than one unique value of nif , then you would want the following: 现在,如果您的意思是给定的num_sumnum_sum应该存在一个以上的nif唯一值,那么您将需要以下内容:

SELECT num_sum
  FROM sumcon
 GROUP BY num_sum
HAVING COUNT(DISTINCT nif) > 1;

If you need to get all the values of nif for which this is the case, then you would have to do something like this: 如果您需要获取所有在这种情况下的nif值,则必须执行以下操作:

SELECT nif, num_sum FROM sumcon
 WHERE num_sum IN (
    SELECT num_sum
      FROM sumcon
     GROUP BY num_sum
    HAVING COUNT(DISTINCT nif) > 1
);

Hope this helps. 希望这可以帮助。

不确定是否正是您要的内容,但我希望它能对您有所帮助。

select nif, num_sum from sumcon group by nif, num_sum having count(1) > 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM