[英]Oracle query optimisation without sub-query
I am looking to make my query more optimized and simpler.我希望使我的查询更加优化和简单。 I have to fetch only those T_ID's whose score is maximum and if that T_ID has a Msg 'C' then it should not be included.我只需要获取那些得分最高的 T_ID,如果那个 T_ID 有 Msg 'C' 那么它不应该被包括在内。
My data looks like:我的数据看起来像:
My Query is:我的查询是:
SELECT DISTINCT T_ID, Msg, MAX(Score) over (Partition by T_ID)
FROM Sample
WHERE T_ID NOT IN (SELECT T_ID FROM Sample WHERE Msg = 'C');
My Answer is:我的回答是:
Is there any way to achieve this by calling the database only once.有没有办法通过只调用一次数据库来实现这一点。
Tip #1: Images are not conducive to building a test case with your data:-(提示 #1:图像不利于用您的数据构建测试用例:-(
But you could do something like this, assuming "0" is a suitable boundary (or perhaps -1)但是你可以做这样的事情,假设“0”是一个合适的边界(或者可能是-1)
SQL> with t as (
2 select 77 t_id, 'N' msg, 220 score from dual union all
3 select 77 t_id, 'C' msg, 220 score from dual union all
4 select 1 t_id, 'N' msg, 120 score from dual union all
5 select 1 t_id, 'N' msg, 102 score from dual union all
6 select 2 t_id, 'N' msg, 112 score from dual union all
7 select 2 t_id, 'C' msg, 152 score from dual union all
8 select 3 t_id, 'N' msg, 172 score from dual union all
9 select 3 t_id, 'N' msg, 192 score from dual union all
10 select 4 t_id, 'N' msg, 100 score from dual union all
11 select 5 t_id, 'N' msg, 101 score from dual
12 )
13 select t_id, max(score)
14 from t
15 group by t_id
16 having min(decode(msg,'C',0,score)) > 0;
T_ID MAX(SCORE)
---------- ----------
1 120
4 100
5 101
3 192
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.