![](/img/trans.png)
[英]A better alternative to ROW_NUMBER to retrieve a single record per group
[英]Using row_number (or alternative) to count by group, and also only distinct per group?
我正在嘗試使用row_number()
計算每個帳戶ID的不同值
這是我擁有的數據的一個示例:
ID | val
_____________
1 | a
1 | a
1 | b
2 | a
3 | c
3 | a
3 | b
4 | d
4 | d
5 | a
我想基本上計算每個唯一ID的唯一值。 我已經嘗試過使用row_number() partition over
。
這是我想要的輸出示例:
ID | val | rank | count
_____________
1 | a | 1 | 2
1 | b | 2 | 3
2 | a | 1 | 1
3 | c | 1 | 1
3 | a | 2 | 1
3 | b | 3 | 3
4 | d | 1 | 2
4 | e | 2 | 2
5 | a | 1 | 1
我已經試過了:
%sql
-- Show
select * from (
select `ID`,`val`, dense_rank() over (partition by `ID` order by `val` asc) as row_num
from table1
)
order by `ID` asc
它將根據新ID重置計數,但不計算不同的val。 又名給我這個:
ID | val | rank
_____________
1 | a | 1
1 | a | 2
1 | b | 3
2 | a | 1
3 | c | 1
3 | a | 2
3 | b | 3
3 | b | 4
3 | b | 5
4 | d | 1
4 | d | 2
4 | e | 3
4 | e | 4
5 | a | 1
您可以使用dense_rank()
進行排序。 。 。
select id, val, dense_rank() over (partition by id order by val) as seqnum
from t;
但是,結果排名將按字母順序排列。 您的樣本表明您想保留原始順序。 如果是這樣,則首先需要一個表示順序的列。 然后,您可以使用兩種聚合級別:
select id, val, dense_rank() over (partition by id order by min_oc)
from (select t.*, min(<ordering column>) over (partition by id, val) as min_oc
from t
) t
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.