0

我正在使用以下 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 列进行运行总和,并将其放入自己的列(称为总计)中,如下所示。

想要的结果

 ****************************************************
    |  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        |

问题

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

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


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

它似乎对每个单词进行排名,因此最低字数从 1 开始,然后如果有 2 个字数相等的单词,它会按字母顺序列出它们。

4

1 回答 1

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;
于 2013-05-03T12:13:58.983 回答