gpt4 book ai didi

mysql - Sql 查询分组和限制

转载 作者:行者123 更新时间:2023-11-29 19:03:07 26 4
gpt4 key购买 nike

我有以下 sql 查询,它根据 topicName 列进行分组(它还进行一些除法运算)。 我想为每个分组主题获取 2 行,而不是全部。

    SELECT wwt.topicName, t.topic_cnt as sumOfWordsInTopic,
wwt.word, wwt.wordCount,
(wwt.wordCount / t.topic_cnt) AS wordProbability
FROM weightallofwordsintopic as wwt JOIN
(SELECT topicName, sum(wordCount) AS topic_cnt
FROM weightallofwordsintopic
GROUP BY topicName
) t
ON wwt.topicName = t.topicName

主题表中的所有单词的权重如下;

topicName | word | wordCount
---
topic0 | word1 | 10
topic0 | word2 | 20
topic0 | word3 | 30
topic0 | word4 | 40
topic0 | word5 | 50
topic0 | word6 | 60

topic1 | word7 | 10
topic1 | word8 | 20
topic1 | word9 | 30
topic1 | word10 | 40
topic1 | word11 | 50
topic1 | word12 | 60

topic2 | word13 | 10
topic2 | word14 | 20
topic2 | word15 | 30
topic2 | word16 | 40
topic2 | word17 | 50
topic2 | word18 | 60

我希望输出为(根据其权重排序,但在这里我只是放置一个示例(上面的选择查询返回一些不同的列))我想根据每个分组 topicName 在列中的权重将上述查询限制为 2 行。

topicName | word | wordCount

topic0 | 1 | 60
topic0 | 1 | 50

topic1 | 1 | 60
topic1 | 1 | 50

topic2 | 1 | 60
topic2 | 2 | 50

最佳答案

在 MySQL 中,最简单的方法可能是使用变量:

SELECT t.*
FROM (SELECT wwt.topicName, t.topic_cnt as sumOfWordsInTopic, wwt.word, wwt.wordCount,
(wwt.wordCount / t.topic_cnt) AS wordProbability,
(@rn := if(@t = wwt.topicName, @rn + 1,
if(@t := wwt.topicName, 1, 1)
)
) as rn
FROM weightallofwordsintopic as wwt JOIN
(SELECT topicName, sum(wordCount) AS topic_cnt
FROM weightallofwordsintopic
GROUP BY topicName
) t
ON wwt.topicName = t.topicName CROSS JOIN
(SELECT @t := '', @rn := 0) params
ORDER BY wwt.topicName, wwt.wordCount DESC
) t
WHERE rn <= 2;

关于mysql - Sql 查询分组和限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43707116/

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