如何使用mysql创建一个带有wordcount运行总和的列?

时间:2013-05-03 12:05:29

标签: mysql

我正在使用以下sql组合2个表,然后计算结果

SELECT td.word, COUNT( instance ) AS wordcount
        FROM ws_words td
        LEFT JOIN ws_missed_words t ON ( t.wordID = td.wordID )
        WHERE quizID =1
        GROUP BY td.word

结果给出

*****************************
|  word  |      wordcount   |
*****************************
|  list  |         3        |
|  miss  |         1        |
|  skip  |         1        |
| another|         0        |

我想再添加一列。我想对wordcount列进行运行总和并将其放入自己的列(称为total),如下所示。

想要的结果

 ****************************************************
    |  word  |      wordcount   |   totalwordcount  |
    *************************************************
    |  list  |         3        |     3             |
    |  miss  |         1        |     4             |
    |  skip  |         1        |     5             |
    | another|         0        |     5             |

我尝试了以下

SELECT td.word, COUNT( instance ) AS wordcount, SUM(wordcount) AS totalwordcount
FROM ws_words td
LEFT JOIN ws_missed_words t ON ( t.wordID = td.wordID )
WHERE quizID =1
GROUP BY td.word

但我收到了错误

#1054 - Unknown column 'wordcount' in 'field list'

接下来我尝试了

SELECT atable.word, atable.wordcount, SUM(atable.wordcount) AS totalwordcount FROM
(SELECT td.word, COUNT( instance ) AS wordcount
FROM ws_words td
LEFT JOIN ws_missed_words t ON ( t.wordID = td.wordID )
WHERE quizID =1
GROUP BY td.word) AS atable

但我得到类似的东西

************************************************
|  word  |      wordcount   |   totalwordcount |
************************************************
|  list  |         1        |         5        |

问题

如何创建一个包含wordcount运行总和的列?

更新草莓的方法给我下面的代码


|  word  |      wordcount   |   running         |
*************************************************
| another|         0        |     1             |
|  miss  |         1        |     2             |
|  skip  |         1        |     3             |
|  list  |         3        |     4             |

似乎是对每个单词进行排名,所以最低的wordcount从1开始,然后如果有2个单词的wordcount,则按字母顺序列出它们。

1 个答案:

答案 0 :(得分:1)

未经测试,'因为你没有给我们任何测试 - 但是一种方式可能是这样的......

 SELECT x.*, COUNT(*) running
   FROM
      ( SELECT td.word
                  , COUNT( t.instance ) wordcount
               FROM ws_words td
               LEFT 
               JOIN ws_missed_words t 
                 ON t.wordID = td.wordID 
              WHERE td.quizID = 1 
              GROUP 
                 BY td.word
      ) x
   JOIN
      ( SELECT td.word
             , COUNT( t.instance ) wordcount
          FROM ws_words td
          LEFT 
          JOIN ws_missed_words t 
            ON t.wordID = td.wordID 
         WHERE td.quizID = 1 
         GROUP 
            BY td.word
      ) y
     ON y.wordcount < x.wordcount
     OR y.wordcount = x.wordcount
    AND y.word < x.word
  GROUP
     BY x.word;