search

Home  >  Q&A  >  body text

Reorganized title: Calculating the total value of other columns using MySQL's Group By and Sum

<p>I have two columns like this: </p> <table class="s-table"> <thead> <tr> <th>Word</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>dog</td> <td>1</td> </tr> <tr> <td>dog</td> <td>5</td> </tr> <tr> <td>Elephant</td> <td>2</td> </tr> </tbody> </table> <p>I want to sum the amounts and get the result</p> <table class="s-table"> <thead> <tr> <th>Word</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>dog</td> <td>6</td> </tr> <tr> <td>Elephant</td> <td>2</td> </tr> </tbody> </table> <p>What I have tried (and failed) so far is: </p> <pre class="brush:php;toolbar:false;">SELECT word, SUM(amount) FROM `Data` GROUP BY 'word'</pre> <p><br /></p>
P粉908138620P粉908138620460 days ago535

reply all(2)I'll reply

  • P粉165522886

    P粉1655228862023-08-28 13:50:14

    It should be accented symbol instead of single quote :

    SELECT word, SUM( amount )
    FROM Data
    GROUP BY `word`;

    Output:

    word     SUM(amount)
    dog           6
    Elephant      2

    reply
    0
  • P粉377412096

    P粉3774120962023-08-28 10:40:51

    Remove the single quotes around WORD. It causes column names to be converted to strings.

    SELECT word, SUM(amount) 
    FROM Data 
    Group By word

    reply
    0
  • Cancelreply