2017-02-22 106 views
0

我正在执行一个查询,并得到一个结果集,其中有两个几乎相同的行,其中只有一个列值不同 - 'EXPLICIT_PERM'。丢弃几乎相同的行集

查询本身很长,我不能在这里发布它,但我可以说查询中'EXPLICIT_PERM'的值是作为另一列值的结果而确定的,它的结构如下所示:

SELECT * FROM ((QUERY1)UNION ALL (QUERY2) UNION ALL (QUERY3)); 

该查询返回许多结果,但在极少数情况下可能发生此重复情况。

QUERY RESULTS

有没有办法,如果我得到两个相同的SERVER_IDs我可以检查和丢弃的结果,包含“0”作为EXPLICIT_PERM?

+1

如何简单地使用外侧的位置,我的意思是脱离了union的括号? –

+0

我需要放弃EXPLICIT_PERM = 0的行,只有在服务器ID出现两次的情况下,我该如何检测? –

+0

为什么你想用PL/SQL(一种编程语言)而不是SQL来解决这个问题? –

回答

2

如果我理解的很好,这可能是一种方法。 假设你已经拥有你[R查询得到的结果,你可以用这种方式:

with yourResult(server_id, server_name, explicit_perm, rank, total) as (
    select 93, 'AVIZNER', 1, 1, 10 from dual union all 
    select 93, 'AVIZNER', 0, 6, 10 from dual union all 
    select 11, 'XXXXXXX', 1, 1, 10 from dual union all 
    select 22, 'YYYYYYY', 0, 1, 10 from dual union all 
    select 11, 'ZZZZZZZ', 1, 1, 11 from dual union all 
    select 11, 'ZZZZZZZ', 1, 2, 22 from dual union all 
    select 11, 'ZZZZZZZ', 0, 1, 10 from dual 
) 
select server_id, server_name, explicit_perm, rank, total 
from (
     select server_id, server_name, explicit_perm, rank, total, 
       count (case when explicit_perm = 1 then 1 end) over (partition by server_id) as count_perm_1 
     from yourResult 
    ) 
where not (explicit_perm = 0 and count_perm_1 > 0)  

这种计算行数与explicit_perm = 1为每server_id,然后排除所有explicit_perm = 0和至少一行行与explicit_perm = 1存在相同的server_id

与我的样本数据,结果:

SERVER_ID SERVER_ EXPLICIT_PERM  RANK  TOTAL 
---------- ------- ------------- ---------- ---------- 
     11 ZZZZZZZ    1   2   22 
     11 ZZZZZZZ    1   1   11 
     11 XXXXXXX    1   1   10 
     22 YYYYYYY    0   1   10 
     93 AVIZNER    1   1   10 
+0

完美地工作,谢谢。 –

+0

我刚刚注意到,将这添加到我的查询后,ORDER BY我执行得到了混乱。我不按'server_id'列排序,但是当我从查询中删除这部分时,订单恢复正常。任何想法为什么? –

+1

在外部查询中,不能依赖没有ORDER BY的顺序。如果您需要订购某些条件,唯一安全的方法是在查询中添加ORDER BY子句以包装您最初的查询。 – Aleksej

1

典型的方法是排名你的结果行(在你的情况下每SERVER_ID),并保持最佳排名。你用ROW_NUMBER来做到这一点。

select * 
from 
(
    select 
    row_number() over (partition by server_id order by explicit_term desc) as rn, 
    q.* 
    from (<your query>) q 
) 
where rn = 1; 
0

除了所有其他有趣的解决方案。我们也可以尝试group by子句

SELECT service_id, 
     server_nam, 
     max(explicit_perm) explicit_perm, 
     rank, 
     total 
FROM ((QUERY1)UNION ALL (QUERY2) UNION ALL (QUERY3)) 
group by service_id, server_nam, rank, total; 
相关问题