简体   繁体   English

甲骨文使用排名

[英]oracle group by using rank

TableOne TableOne

Id1| Level     |Type|Survey Nr
--------------------------------
  1| Level 1   |A   |1  
  2| Level 2   |A   |1
  3| Level 3   |A   |1
  4| All Levels|A   |1   
 ------------------------------- 
  5| Level 1   |B   |1 
  6| Level 2   |B   |1
  7| Level 4   |B   |1
 -------------------------------- 
  8| Level 1   |A   |2 
  9| Level 2   |A   |2
 10| Level 3   |A   |2
 11| All Levels|A   |2      

I want to group my data by type and survey Nr an the output of my query to be 我想按类型对数据进行分组并调查Nr,查询的输出为

1. All levels   |A   |1
2. Level 1      |B   |1 
3. Level 2      |B   |1
4. Level 4      |B   |1
5. All Levels   |A   |2

So when my subgroup Type/survey nr have level "All Levels" i will only display that record like in case A -1 and A2 else i want to display all records like in case B-1. 因此,当我的子类型/调查组的级别为“所有级别”时,我只会显示情况A -1和情况A2之类的记录,否则我想显示所有情况B-1的情况。

I'd just UNION ALL the data where you have the string 'All Levels' to the data where it doesn't exist within that group. 我只是将所有具有字符串'All Levels'的数据与该组中不存在的数据联合起来。 I've effectively assumed that your table is unique on LEVEL, TYPE and SURVEY_NR. 我已经有效地假设您的表在LEVEL,TYPE和SURVEY_NR上是唯一的。

with base_data as (
 select a
   from the_table
        )
select level, type, survey_nr
  from base_data
 where level = 'All Levels'
 union all
select level, type, survey_nr
  from base_data
 where not exists ( select 1
                      from base_data
                     where level = 'All Levels'
                       and type = x.type
                       and survey_nr = x.survey_nr
                           )

Please note that LEVEL is normally an invalid name for a column; 请注意,LEVEL通常是列的无效名称; it's worth changing it. 值得更改。

You can do this with the RANK() function and a CASE statement: 您可以使用RANK()函数和CASE语句来做到这一点:

WITH cte AS (SELECT "Id1","Lev","Type","Survey_Nr"
                    ,RANK() OVER (PARTITION BY "Type","Survey_Nr" ORDER BY CASE WHEN "Lev" = 'All Levels' THEN 0 ELSE 1 END) AS RN
             FROM Table1)
SELECT *
FROM cte
WHERE RN = 1
ORDER BY "Id1"

Demo: SQL Fiddle 演示: SQL Fiddle

RANK() will assign a rank value to each set indicated in the PARTITION BY clause, and the CASE statement in the ORDER BY is used to set all values of Lev into one of two categories, giving preference to the "All Levels" values. RANK()将为PARTITION BY子句中指示的每个集合分配一个等级值,并且ORDER BYCASE语句用于将Lev的所有值设置为两个类别之一,优先考虑“所有级别”值。 Running this without the WHERE clause will help you see how the RANK() function is working. 在不使用WHERE子句的情况下运行此命令将帮助您了解RANK()函数的工作方式。

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

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