根据优先级获取数据

时间:2016-06-03 07:25:46

标签: sql oracle

我的表格结构如下:

enter image description here

'类型' column有三种类型的值,即1,2和3。

每种类型都有一定的规则(在RULE专栏中提到) 相同的规则可以与多个类型记录相关联。 现在我想只将那些记录作为具有更高价值的输出。 例如: '板凳类型'是与1,2和3类型相关联的规则,因此我们将选择带有类型3的值的Rule,即Single。 '复杂性'是1型和1型2所以我们将选择规则值5。 如果规则只存在于一个类型中,那么它将按原样被选中。

我尝试了以下查询,但它正在使用Type 1& 2。

select *
FROM CX_ROSTER_RULES_VIEW v
INNER JOIN 
(
select RULE, MAX("Type") AS MAX_TYPE
FROM CX_ROSTER_RULES_VIEW
GROUP BY RULE
) v1
ON v.RULE = v1.RULE
AND v."Type" = v1.MAX_TYPE
WHERE ( branch = 'Civil' AND category = 'C.M. (Civil)' AND sub_category = 'Pauper' )        
       OR ( branch = 'Civil' AND category = 'C.M. (Civil)' AND sub_category IS NULL )
        OR ( branch = 'Civil' AND category IS NULL AND sub_category IS NULL ) 

3 个答案:

答案 0 :(得分:1)

使用ROW_NUMBER()分析功能,您无需进行自我加入:

SELECT *
FROM   (
  SELECT v.*,
         ROW_NUMBER() OVER ( PARTITION BY Rule ORDER BY "Type" DESC ) AS rn
  FROM   CX_ROSTER_RULES_VIEW v
  WHERE branch = 'Civil'
  AND   (  category IS NULL 
        OR ( category = 'C.M. (Civil)'
           AND ( sub_category IS NULL OR sub_category = 'Pauper' )
           )
        )
)
WHERE  rn = 1;

答案 1 :(得分:0)

我会这样做的。

(select rule, max(type) as type from yourtable
group by rule) --this will give you the rule with the highest priority

用它做这个

select m.* from CX_ROSTER_RULES_VIEW as m inner join (select rule, max(type) as type from CX_ROSTER_RULES_VIEW
    group by rule) p on m.rule = p.rule and m.type = p.type
如果上面没有工作,请不要在这台机器上使用sql。如果你没有完成,我明天就能测试。

select m.* from (select rule, max(type) as type from CX_ROSTER_RULES_VIEW
            group by rule) as p left join CX_ROSTER_RULES_VIEW  as m on p.rule = m.rule and p.type = m.type

它几乎相同,只是想看看左连接是否会做任何不同的事情。

答案 2 :(得分:0)

试试这个:

select v.* from 
CX_ROSTER_RULES_VIEW v join  
(select rule, max(type) as maxType from  CX_ROSTER_RULES_VIEW group by rule) M
on v.Rule = M.Rule and v.type = M.maxType