gpt4 book ai didi

sql - 查找出现在多列中的项目数

转载 作者:行者123 更新时间:2023-11-29 14:19:41 25 4
gpt4 key购买 nike

假设一张 table

source_document_id BIGINT NOT NULL,
target_document_id BIGINT NOT NULL,
similarity DOUBLE NOT NULL,

如果我想确定 source_document_id 列中文档的出现频率,我的查询将运行如下:

select count(source_document_id) as c1, source_document_id from PROJECT_0622.SIMILARITY_RESULT group by source_document_id order by  c1 desc;

但考虑到文档 ID 可能出现在 source_document_id 或 target_document_id 列中,...我如何找到任一列中出现 documentId 的频率?

例如,这样考虑数据

source_document_id source_document_id similarity
1 2 0.8
1 3 0.8
1 4 0.7
4 5 0.8
4 8 0.75
9 4 0.9
2 4 0.99

我想达到这样的结果

frequency in source/target doc id column, doc_id
5 4
3 1
2 2
1 8
1 3
1 9
1 10

这可能吗?谢谢

最佳答案

有可能将数据聚合两次会有更好的性能:

select id, sum(cnt) as n_docs
from ((select source_document_id as id, count(*) as cnt
from similarity
group by source_document_id
) union all
(select target_document_id as id
from similarity
group by target_document_id
)
) t
group by id;

如果性能是一个考虑因素,两种方法都值得尝试,尤其是当两列上都有索引时。

关于sql - 查找出现在多列中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725827/

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