简体   繁体   English

将值与平均值进行比较 SQL

[英]Compare a value to an average value SQL

I have a database with some persones stored in it, this persons have a residuallLave (holiday days they haven´t needed).我有一个数据库,其中存储了一些人,这些人有一个剩余的Lave(他们不需要的假期)。 Now I want to get the average value of this residualLeave and compare which persons have more than the average.现在我想得到这个residualLeave 的平均值并比较哪些人比平均值多。 But I get only one person back and this can't be true because there are more persons with a more residualLeave.但是我只回了一个人,这不可能是真的,因为有更多的人有更多的剩余离开。

Code:代码:

在此处输入图片说明

Output:输出:

在此处输入图片说明

Your query won't work because you compare "normal" columns with aggregated ones without grouping.您的查询将不起作用,因为您将“正常”列与未分组的聚合列进行比较。 It is way simpler like this:像这样更简单:

select *
from tpersons
where residualLeave > (select avg(residualLeave) from tpersons)

Just for fun, here is a MySQL 8+ version using analytic functions:只是为了好玩,这是一个使用分析函数的 MySQL 8+ 版本:

SELECT persid, firstname, lastname, residualleave
FROM (SELECT *, AVG(residualleave) OVER () AS avgresidualleave FROM tpersons) t
WHERE residualleave > avgresidualleave;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM