2017-04-30 3 views
0

Ich habe folgende SQL-Abfrage ist es gruppieren nach thisyname Spalte (auch macht es einige Division-Operation). Ich möchte 2 Zeilen für jedes gruppierte Thema nicht alle erhalten.Sql Query Grouping und Begrenzen

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 Tabelle ist als;

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 

Ich möchte Ausgabe (Bestellung nach ihrem Gewicht, aber hier habe ich eine Probe nur einige differents Spalten) setzen (wählen Sie Abfragen über Returns) werden I für jede gruppiert topicname obige Abfrage auf 2 Zeile begrenzen wollen nach zu ihrem Gewicht in der Spalte.

topicName | word | wordCount 

topic0 | 1  | 60 
topic0 | 1  | 50 

topic1 | 1  | 60 
topic1 | 1  | 50 

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

Siehe http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems -zu-ich-bin-eine-sehr-einfache-sql-Abfrage – Strawberry

Antwort

0

In MySQL, wahrscheinlich die einfachste Methode ist Variablen zu verwenden:

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

Danke Sir, danke für Ihre magische Note @Gordon Linoff – mstfky

0

Ich bin ziemlich neu mich, aber ich glaube, wenn Sie TOP verwenden, in der SELECT-Anweisung, die den Trick tun würde. Etwas wie: 'SELECT TOP 2 wwt.topicName, etc.