SQL中的排名和分区查询

时间:2017-05-22 16:04:38

标签: sql rank partition

我在AS400中有一个表格,如下所示

ActorGarbageCollectionSettings

我需要的是具有状态Y的每种类型的前2名。结果应该是Type Values Status A 1 Y A 2 N A 3 Y A 4 Y A 5 N B 2 Y B 7 N C 3 Y C 5 N C 4 Y C 6 Y C 7 Y C 1 Y D 3 Y D 5 Y E 7 N E 4 N E 3 Y E 6 N E 7 Y E 8 N

我使用的查询是

A 1 , A 3, B 2 , C3, C4, D3, D5, E3, E7.

这里的问题是它不会事先过滤掉状态。它拿起前2,然后用Y过滤掉。所以结果看起来像A1而不是A1和A3,因为它首先选择A1和A2,然后过滤掉A2。 我在哪里插入Status = y以获得更准确的结果。 我是SQL的新手,所以如果有更好的方式来编写上面的查询,我很好。

1 个答案:

答案 0 :(得分:0)

这个outta做到了。使用with子句将过滤后的结果提供给新查询,然后您可以对其进行排名。

with testtable (type, value, status) as (
select 'A', 1, 'Y' from dual union all
select 'A', 2, 'N' from dual union all
select 'A', 3, 'Y' from dual union all
select 'A', 4, 'Y' from dual union all
select 'A', 5, 'N' from dual union all
select 'B', 2, 'Y' from dual union all
select 'B', 7, 'N' from dual union all
select 'C', 3, 'Y' from dual union all
select 'C', 5, 'N' from dual union all
select 'C', 4, 'Y' from dual union all
select 'C', 6, 'Y' from dual union all
select 'C', 7, 'Y' from dual union all
select 'C', 1, 'Y' from dual union all
select 'D', 3, 'Y' from dual union all
select 'D', 5, 'Y' from dual union all
select 'E', 7, 'N' from dual union all
select 'E', 4, 'N' from dual union all
select 'E', 3, 'Y' from dual union all
select 'E', 6, 'N' from dual union all
select 'E', 7, 'Y' from dual union all
select 'E', 8, 'N' from dual
)
, ys as (
select
*
from testtable
where STATUS = 'Y'
)
, yrank as (
select
type, 
value,
status,
rank() over(partition by type order by value) Y_RANK
from ys
)
select
*
from yrank
where Y_RANK <= 2