[英]SQL, label user based on the similarity
SQL 中可能出現以下情況嗎?
假設我有一張這樣的桌子:
用戶身份 | 產品編號 |
---|---|
1個 | 123 |
1個 | 122 |
1個 | 121 |
2個 | 124 |
2個 | 125 |
2個 | 121 |
3個 | 123 |
3個 | 122 |
3個 | 122 |
4個 | 123 |
4個 | 212 |
4個 | 222 |
5個 | 124 |
5個 | 125 |
5個 | 121 |
我想要 label 用戶,如果他們有相同的 product_id,不管順序如何,所以 output 看起來像這樣:
用戶身份 | 產品編號 | label |
---|---|---|
1個 | 123 | 一種 |
1個 | 122 | 一種 |
1個 | 121 | 一種 |
2個 | 124 | b |
2個 | 125 | b |
2個 | 121 | b |
3個 | 123 | 一種 |
3個 | 121 | 一種 |
3個 | 122 | 一種 |
4個 | 123 | c |
4個 | 212 | c |
4個 | 222 | c |
5個 | 124 | b |
5個 | 125 | b |
5個 | 121 | b |
請指教
您可以使用string_agg
function 獲取每個用戶的 product_ids 列表(作為單個字符串),然后對該字符串使用dense_rank
function 以獲取每個 product_ids 列表的唯一標簽。
select T.user_id, T.product_id, D.label
from table_name T join
(
select user_id,
chr(dense_rank() over (order by user_products) + 96) label
from
(
select user_id,
string_agg(cast(product_id as string), ',' order by product_id) user_products
from table_name
group by user_id
) lbl
) D
on T.user_id = D.user_id
order by T.user_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.