Home  >  Q&A  >  body text

How to use sum function to filter window functions in MYSQL

<p>How can I write this query to filter out only results with a sum greater than 50? I can't get it to work using having or sum, but I'm sure there is some way. </p> <pre class="brush:php;toolbar:false;">select name, sum(score) from submissions inner join hacker on submissions.hacker_id = hacker.hacker_id group by submissions.hacker_id order by sum(score) desc having sum(score) > 50</pre> <p>Here is an example with a table (there is nothing special about the table, this query runs without the last row, but returns everyone's score and name): http://sqlfiddle.com/# !9/7a660d/16</p>
P粉186904731P粉186904731438 days ago567

reply all(2)I'll reply

  • P粉877114798

    P粉8771147982023-08-31 15:51:51

    Order by should be in last

    select name, sum(score) 
    from submissions 
    inner join hacker on submissions.hacker_id = hacker.hacker_id
    group by submissions.hacker_id
    having sum(score) > 50 
    order by sum(score) desc

    Sort according to what should be at the end

    选择 名称, 总分
    从 提交
    内连接 黑客 on 提交.黑客编号 = 黑客.黑客编号
    分组 按 提交.黑客编号
    筛选 总分 > 50 
    排序 按 总分 降序

    reply
    0
  • P粉909476457

    P粉9094764572023-08-31 00:57:15

    Your order by should be after your having. Right now:

    select 
        name, 
        sum(score) 
    from 
        submissions 
    inner join 
        hacker on submissions.hacker_id = hacker.hacker_id
    group by 
        submissions.hacker_id
    having 
        sum(score) > 50 
    order by 
        sum(score) desc
    

    reply
    0
  • Cancelreply