在 Oracle 中,在忽略负匹配记录的同时获取最大值
In Oracle, get max value while ignoring negative matching records
我有一个 table,如下所示:
ID Value
462338900 41040
462338900 -41040
462338900 50
462338900 0
我想做的是从此 table 中获取最大值,其中值字段没有匹配的负记录。在上面的示例中,41040 将是最大值。但是,由于它有负匹配记录 -41040,我想 "throw it out" 并带回新的最大值 50。
这是一个使用exists
的方法:
select id, max(value)
from t
where not exists (select 1
from t t2
where t2.id = t.id and t2.value = - t.value
)
group by id;
我对 Gordon 的回答投了赞成票 -- 这是正确的回答。但是,根据您的 table 有多大以及您一次要处理多少 ids
,这可能会表现得更好,因为它只读取 table 一次。也就是说,它不需要 not exists
需要的 ANTI JOIN 操作。
select id, max(value)
from (
select id, abs(value) value, count(case when value < 0 then 1 else null end) neg_count
from t
group by id, abs(value) )
where neg_count = 0
group by id;
还有,小心点.. 你把你的要求说得很具体了。如果您的数据是
ID Value
462338900 41040
462338900 41040
462338900 -41040
462338900 50
462338900 0
... 值 41040 重复,-41040 的单次出现将从结果中排除两者,最大值为 50。如果在这种情况下您希望最大值为 41040,则这是一个不同的查询.我的版本比 not exists
方法更适应 table 要求:您可以计算类似于 neg_count
的 pos_count
并将 where neg_count=0
更改为 where pos_count > neg_count
.
我有一个 table,如下所示:
ID Value
462338900 41040
462338900 -41040
462338900 50
462338900 0
我想做的是从此 table 中获取最大值,其中值字段没有匹配的负记录。在上面的示例中,41040 将是最大值。但是,由于它有负匹配记录 -41040,我想 "throw it out" 并带回新的最大值 50。
这是一个使用exists
的方法:
select id, max(value)
from t
where not exists (select 1
from t t2
where t2.id = t.id and t2.value = - t.value
)
group by id;
我对 Gordon 的回答投了赞成票 -- 这是正确的回答。但是,根据您的 table 有多大以及您一次要处理多少 ids
,这可能会表现得更好,因为它只读取 table 一次。也就是说,它不需要 not exists
需要的 ANTI JOIN 操作。
select id, max(value)
from (
select id, abs(value) value, count(case when value < 0 then 1 else null end) neg_count
from t
group by id, abs(value) )
where neg_count = 0
group by id;
还有,小心点.. 你把你的要求说得很具体了。如果您的数据是
ID Value
462338900 41040
462338900 41040
462338900 -41040
462338900 50
462338900 0
... 值 41040 重复,-41040 的单次出现将从结果中排除两者,最大值为 50。如果在这种情况下您希望最大值为 41040,则这是一个不同的查询.我的版本比 not exists
方法更适应 table 要求:您可以计算类似于 neg_count
的 pos_count
并将 where neg_count=0
更改为 where pos_count > neg_count
.