1

我试图从按 spot_id 和 vote_type 分组的表中获取最大总行数,但我需要的另一个字段(video_id)不在组中,所以我想这就是为什么它在结果集中给出了错误的 video_id。我的查询有什么问题?

询问:

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

子查询结果:

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'

实际结果:

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

预期结果:

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

2 回答 2

1

如果不按 video_id 字段分组,您将收到来自相应分组字段的仲裁值。

一种选择是将最大查询的结果加入到自身中——如下所示:

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
于 2013-06-13T04:19:06.657 回答
0

尝试将 video_id 添加到最终组中

于 2013-06-13T04:42:42.150 回答