简体   繁体   中英

MAX on columns generated by SUM and GROUP BY

I'm trying to get the MAX on a column which is generated dynamically using the SUM statement. The SUM statement is used together with the 'GROUP by' syntax.

This is the original query, however it needs to be modified to work with grouping, sums and of course MAX.

SELECT  SUM(video_plays) AS total_video_plays
    FROM `video_statistics` v_stat
    GROUP BY v_stat.`video_id` ASC

As you can see SUM is adding all the values inside video_plays as total_video_plays ..

But I SIMPLY want to get the MAX of total_video_plays

My attempts are below, however they do not work..

SELECT SUM(video_plays) AS MAX(total_video_plays)
    FROM `video_statistics` v_stat
    GROUP BY v_stat.`video_id` ASC

How would you get the MAX on a column made dynamically without using subqueries - Because the above is already placed within one.

Something like

SELECT SUM(video_plays) AS total_video_plays
FROM `video_statistics` v_stat
GROUP BY v_stat.`video_id` 
ORDER BY total_video_plays DESC 
LIMIT 1 

Hat Tip OMG Ponies for proper MySQL dialect.

如果没有子查询,你就无法做你想要的事情,因为你不能运行两个聚合函数,一个在另一个之上。

Will this work for you?

SELECT MAX(total_video_plays) from table (
 SELECT SUM(video_plays) AS total_video_plays
    FROM `video_statistics` v_stat
    GROUP BY v_stat.`video_id` ASC )

It contains a subquery, but maybe not in the sense you were thinking.

can't you just do this?:

SELECT video_id, max(video_plays) AS max_video_plays    
FROM `video_statistics` v_stat    
GROUP BY v_stat.`video_id` ASC

There's an example here:

http://dev.mysql.com/doc/refman/5.1/de/select.html

SELECT user, MAX(salary) FROM users
GROUP BY user HAVING MAX(salary) > 10;

EDIT : second attempt, albeit using a subquery:

select max(sum_video_plays)
from (
SELECT video_id, sum(video_plays) AS sum_video_plays    
FROM `video_statistics` v_stat    
GROUP BY v_stat.`video_id`
) x

Your outer query may well be selecting from a much smaller set, and (depending on your data distribution etc.) may be quite performant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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