Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何使用OVER()函数获取列中的值之和?_Mysql_Count_Window Functions - Fatal编程技术网

Mysql 如何使用OVER()函数获取列中的值之和?

Mysql 如何使用OVER()函数获取列中的值之和?,mysql,count,window-functions,Mysql,Count,Window Functions,所以我有一个表,其中存储了每个学生的信息,他们的出生日期和学校的开始日期。所需的输出是按年龄分组的学生的% Biqquery中的查询编写如下: Select ROUND(100*(Number_of_Students/Total),2) as Percent_Students,Age FROM (SELECT count(participantname) as Number_of_Students, SUM(count(participantname)) OVER() AS Total, C

所以我有一个表,其中存储了每个学生的信息,他们的出生日期和学校的开始日期。所需的输出是按年龄分组的学生的%

Biqquery中的查询编写如下:

Select ROUND(100*(Number_of_Students/Total),2) as Percent_Students,Age FROM

(SELECT count(participantname) as Number_of_Students, 
SUM(count(participantname)) OVER() AS Total,
CAST(round(date_diff(startdate, participantdob,day) / 365.25)  AS INT64) as Age 
FROM `ParticipantEnrolment` 

group by Age
order by Age)
内部查询的输出是

Row Number_of_Students  Total   Age 
1   1                   826     12
2   259                 826     13
3   358                 826     14
4   145                 826     15
5   47                  826     16
6   16                  826     17
其中Total=826是学生人数之和

在WorkBench中尝试相同的查询时,由于OVER()函数,我在内部查询中遇到语法错误。datediff函数更改正在mysql中按预期工作。修订后的查询如下

SELECT count(participantname) as Number_of_Students,
SUM(count(participantname)) OVER() AS TOTAL,
ROUND(timestampdiff(DAY,participantdob,startdate)/365.25) as AGE

FROM `ParticipantEnrolment`
group by AGE
order by AGE

如果删除OVER()语句,查询将正常工作。无法找出这种情况下的语法问题!如果您正在运行MySQL 5.7或更早版本,并且不支持窗口功能,我们将不胜感激。您可以通过子查询解决此问题:

select 
    count(*) as number_of_students,
    (select count(*) from participantenrolment) as total,
    round(timestampdiff(day, participantdob, startdate) / 365.25) as age
from participantenrolment
group by age
order by age

请注意,我将
count(participantname)
替换为
count(*)
:假设
participantname
不可为空,这两个表达式在功能上是等效的,
count(*)
更有效。如果
participantname
是一个可为空的列,您可以将其更改回原来的值。

很可能您正在运行MySQL 5.7或更早版本,其中不支持窗口函数。您可以通过子查询解决此问题:

select 
    count(*) as number_of_students,
    (select count(*) from participantenrolment) as total,
    round(timestampdiff(day, participantdob, startdate) / 365.25) as age
from participantenrolment
group by age
order by age

请注意,我将
count(participantname)
替换为
count(*)
:假设
participantname
不可为空,这两个表达式在功能上是等效的,
count(*)
更有效。如果
participantname
是一个可为空的列,您可以将其更改回原来的值。

您正在运行哪个版本的MySQL?您正在运行哪个版本的MySQL?谢谢。这起作用了。非常感谢你的帮助!非常感谢。这起作用了。非常感谢你的帮助!