-1

我想在表上使用“group by”执行查询,但想对将为每个组选择的记录应用 3 条规则。这可能吗?使用 Mysql SGBD。

idMatch  Country  VideoType VideoId
1        Pt       High      vidZbr  
1        Pt       High      vidXpto
1        Pt       low       vioptr
1        Pt       normal    vidfff
2        Pt       low       vidfgg
2        Pt       normal    vid
3        Pt       low       videop

例子:

SELECT * FROM videos_extended where country = 'Pt' group by idMatch;

分组规则的所需结果:(如果存在则添加视频类型“高”,如果存在则添加视频类型“正常”,如果此“idMatch”组所有其他方法均失败,则添加“低”)

idMatch  Country  VideoType VideoId
1        Pt       High      vidZbr
2        Pt       normal    vid
3        Pt       low       videop
4

2 回答 2

1

这将为该行选择两行:“1”、“Pt”、“High”。如果您指定如何选择 VideoId,则可以改进它:

select *
from videos_extended video inner join
(
    select idMatch, Country, 
       min(case VideoType 
           when 'high' then 1 
           when 'normal' then 2
           when 'low' then 3
           else 4 
         end
       ) rank
    from videos_extended
    group by idMatch, Country
) maxType
on maxType.idMatch = video.idMatch 
   and maxType.Country = video.Country
   and maxType.rank = (
      case video.VideoType 
         when 'high' then 1 
         when 'normal' then 2
         when 'low' then 3
         else 4 
      end
   )
于 2013-04-18T23:37:34.663 回答
0

如果 VideoType 是整数会更好,否则您可以使用 CASE 或此查询:

SELECT idMatch, Country, VideoType, MAX(VideoId) AS MVidId FROM videos_extended INNER JOIN (SELECT idMatch AS idm, MIN(SUBSTRING(VideoType, 3, 1)) AS vv FROM videos_extended GROUP BY idMatch, Country) AS T ON idMatch = idm AND SUBSTRING(VideoType, 3, 1) = vv GROUP BY idMatch, Country, VideoType
于 2013-04-18T23:24:49.160 回答