简体   繁体   中英

SQL MAX with GROUP BY getting wrong non-grouped field

I'm trying to get the maximum total of rows from a table grouped by spot_id and vote_type but the other field I need (video_id) is not in the group, so I guess that's why it's giving the wrong video_id in the result set. what is wrong with my query?

Query:

SELECT 
    max(total_votes) as total, spot_id, vote_type, video_id 
FROM 
    (
    SELECT 
        count(*) as total_votes, spot_id, video_id, vote_type 
    FROM 
        spot_video_votes 
    GROUP BY 
        spot_id, video_id, vote_type
    ) AS t
GROUP BY 
    spot_id, vote_type

Subquery result:

total_votes, spot_id, video_id, vote_type
'1','1','2','OWN'
'1','1','3','OWN'
'4','1','4','OWN' -- should pick this
'1','2','3','FAIL'
'2','2','3','OWN' -- this
'2','2','4','FAIL' -- and this
'1','2','4','OWN'

Actual result:

total, spot_id, video_id, vote_type
'4','1','2','OWN'
'2','2','3','FAIL'
'2','2','3','OWN'

Expected result:

total, spot_id, video_id, vote_type
'4','1','4','OWN'
'2','2','4','FAIL'
'2','2','3','OWN'

Without grouping by the video_id field, you're receiving an arbitraty value from the corresponding grouped fields.

One option is to join to the result of the max query to itself -- something like this:

SELECT t1.total_votes as total, t1.spot_id, t1.vote_type, t1.video_id 
FROM 
    (
    SELECT count(*) as total_votes, spot_id, video_id, vote_type 
    FROM spot_video_votes 
    GROUP BY spot_id, video_id, vote_type
    ) AS t1 JOIN 
    (
    SELECT max(total_votes) as max_total_votes, spot_id, vote_type, video_id 
    FROM 
        (
        SELECT count(*) as total_votes, spot_id, video_id, vote_type 
        FROM spot_video_votes 
        GROUP BY spot_id, video_id, vote_type
        ) AS t
    GROUP BY spot_id, vote_type
    ) t2 ON t1.total_votes = t2.max_total_votes 
           AND t1.spot_id = t2.spot_id 
           AND t1.vote_type = t2.vote_type

尝试将video_id添加到最终分组者

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