gpt4 book ai didi

python - 使用 SQL 提取唯一值

转载 作者:行者123 更新时间:2023-12-01 00:32:57 26 4
gpt4 key购买 nike

我是 SQL 新手,非常感谢您帮助我从 Hive 表中提取数据。该表包含两个相关列:hosturlurl列有很多重复项和类似的 url 重定向到同一页面,格式如下:

https://www.cnn.com/2019/09/20/politics/
https://www.cnn.com/2019/09/20/politics
http://www.cnn.com/2019/09/20/politics/
http://www.cnn.com/2019/09/20/politics

主机格式示例:

https://www.cnn.com/
http://www.cnn.com/

我需要一个查询来提取唯一的网址,并优先选择 https版本超过http以及带有尾部斜杠的 url 覆盖不带尾部斜杠的 url(如果可用)。因此,对于上面的示例,结果应该是:

https://www.cnn.com/2019/09/20/politics/

一个简单的 bash 或 python 脚本对本地文件执行相同的操作也会非常有帮助。

最佳答案

Hive 的解决方案。使用 row_number() 删除重复项。查看protocol_keypath_key是如何计算的,它们在row_number()partition by子句中使用:

with your_data as (--use your table instead of this
select stack( 4,
'https://www.cnn.com/2019/09/20/politics/',
'https://www.cnn.com/2019/09/20/politics',
'http://www.cnn.com/2019/09/20/politics/',
'http://www.cnn.com/2019/09/20/politics') as url
) --your table

select url from
(
select s.url, --s.protocol, s.protocol_key, s.host, s.path, s.path_key, --columns for debugging
row_number() over(partition by s.protocol_key, s.host, s.path_key order by s.protocol desc, s.path desc) rn --https and path with/ are preferred
from
(--parse url
select t.url, s.protocol, s.host, s.path, regexp_replace(s.path,'/$','') as path_key, regexp_replace(s.protocol,'s$','') as protocol_key
from your_data t
lateral view parse_url_tuple(url, 'PROTOCOL','HOST', 'PATH')s as protocol, host, path
)s)s where rn = 1
;

结果:

https://www.cnn.com/2019/09/20/politics/

关于python - 使用 SQL 提取唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58035416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com