【问题标题】:Rank and partition query in SQLSQL中的排序和分区查询
【发布时间】:2023-03-27 13:31:01
【问题描述】:

我在 AS400 中有一张如下表

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

我需要的是具有状态 Y 的每种类型的前 2 个。即结果应该类似于A 1 , A 3, B 2 , C3, C4, D3, D5, E3, E7.

我使用的查询是这样的

SELECT type,
    REFERENCES
FROM (
    SELECT type,
        REFERENCES,
        STATUS,
        rank() OVER (PARTITION BY Type ORDER BY REFERENCES DESC) AS Rank
    FROM Tables
    ) a
WHERE rank <= 2
    AND Type IN (A,B,C,D,E)
    AND STATUS = Y;

这里的问题是它没有预先过滤掉状态。它选择前 2 个,然后用 Y 过滤掉。所以结果看起来像 A1 而不是 A1 和 A3,因为它首先选择了 A1 和 A2 ,然后过滤掉了 A2 。 我在哪里插入 Status=y 以获得更准确的结果。 我是 SQL 的新手,所以如果还有更好的方法来编写上述查询,我​​可以接受。

【问题讨论】:

  • 我无法格式化表格以使上面更清晰:)
  • 将 WHERE 子句的 status = Y 位粘贴到子查询中。考虑到您的数据,将Type IN (A,B,C,D,E) 部分也粘贴到您的子查询中是有意义的。
  • @JNevill - 常识但绝对完美。干杯!

标签: sql rank partition


【解决方案1】:

这不行。使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 2021-03-30
    • 2018-06-27
    • 1970-01-01
    相关资源
    最近更新 更多