mysql - Sql 查询分组和限制

标签 mysql sql group-by query-optimization limit

我有以下 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/

相关文章:

javascript - 如何处理nodejs中的大量条件匹配?

mysql - 如何编写基于不同优先级标准分配有限数量位置的 SQL 查询

sql - SQL 中的迭代求和

sql - 分组中最小值的 Oracle 分析函数

MongoDB 选择计数组

python - Pandas 聚合数据框只返回一列

mysql - 插入重复键导致自动增量字段出现问题

mysql - PHP/MySQL - 单击链接更改查询

mysql - 即时提取数据的 mysql 语法是什么

python - Pandas 中的Groupby列后缀