[英]oracle group by using rank
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
我想按类型对数据进行分组并调查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
因此,当我的子类型/调查组的级别为“所有级别”时,我只会显示情况A -1和情况A2之类的记录,否则我想显示所有情况B-1的情况。
我只是将所有具有字符串'All Levels'
的数据与该组中不存在的数据联合起来。 我已经有效地假设您的表在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
)
请注意,LEVEL通常是列的无效名称; 值得更改。
您可以使用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"
演示: SQL Fiddle
RANK()
将为PARTITION BY
子句中指示的每个集合分配一个等级值,并且ORDER BY
的CASE
语句用于将Lev的所有值设置为两个类别之一,优先考虑“所有级别”值。 在不使用WHERE
子句的情况下运行此命令将帮助您了解RANK()
函数的工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.