2017-04-30 46 views
0

我有以下sql查詢它是根據topicName列gruping(也使一些除法操作)。 我想爲每個分組主題獲取2行不是全部。SQL查詢分組和限制

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 

weightallofwordsintopic table is as;

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 

我想輸出爲(按體重排序,但在這裏,我只是把樣品(選擇查詢上面返回一些型動物列)) 我想限制上面查詢到2行中的每個根據分組topicName到他們的重量欄。

topicName | word | wordCount 

topic0 | 1  | 60 
topic0 | 1  | 50 

topic1 | 1  | 60 
topic1 | 1  | 50 

topic2 | 1  | 60 
topic2 | 2  | 50 
+0

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems對我來說是一個非常簡單的sql查詢 – Strawberry

回答

0

在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; 
+0

謝謝先生,謝謝你的魔力觸動@Gordon Linoff – mstfky

0

我非常新我自己,但我相信,如果你使用TOP,在你的SELECT語句,會做的伎倆。例如: 'SELECT TOP 2 wwt.topicName等。