如何用 MYSQL 中的总和过滤 window 函数?
How to filter window function with sum in MYSQL?
如何编写此查询以仅过滤大于 50 的总和?我不能让它与 having 或 sum 一起工作,但我确定有一些方法。
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
Fiddle 和表格在这里(它们没有什么不寻常的,这个查询运行时没有最后一行但是 returns 每个人的分数和名字):http://sqlfiddle.com/#!9/7a660d/16
您的订单应该在您拥有之后。即
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
排序应该在最后
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
您也可以在求和语句中使用 CASE。这种方法适用于 windows 函数,尽管我还没有针对普通的总和聚合函数对其进行测试
选项 1(案例总和):
select name, sum(case when score>50 else 0 end)
from submissions inner join hacker on submissions.hacker_id = hacker.hacker_id
group by submissions.hacker_id
order by sum(score) desc
选项 2 Windows 函数:
select name,
sum(case when score>50 else 0 end) over (partition by submissions.hacker_id)
from submissions inner join hacker on submissions.hacker_id = hacker.hacker_id
group by submissions.hacker_id
order by 子句稍有变化,因此我将其省略,但您随时可以再次添加
如何编写此查询以仅过滤大于 50 的总和?我不能让它与 having 或 sum 一起工作,但我确定有一些方法。
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
Fiddle 和表格在这里(它们没有什么不寻常的,这个查询运行时没有最后一行但是 returns 每个人的分数和名字):http://sqlfiddle.com/#!9/7a660d/16
您的订单应该在您拥有之后。即
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
排序应该在最后
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
您也可以在求和语句中使用 CASE。这种方法适用于 windows 函数,尽管我还没有针对普通的总和聚合函数对其进行测试 选项 1(案例总和):
select name, sum(case when score>50 else 0 end)
from submissions inner join hacker on submissions.hacker_id = hacker.hacker_id
group by submissions.hacker_id
order by sum(score) desc
选项 2 Windows 函数:
select name,
sum(case when score>50 else 0 end) over (partition by submissions.hacker_id)
from submissions inner join hacker on submissions.hacker_id = hacker.hacker_id
group by submissions.hacker_id
order by 子句稍有变化,因此我将其省略,但您随时可以再次添加