簡體   English   中英

SQL中的排名和分區查詢

[英]Rank and partition query in SQL

我在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

我需要的是狀態為Yee的每種類型的前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的新手,所以如果還有更好的方法編寫上述查詢,我​​也很好。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM