Top N Per Group with Multiple Table Joins

前端 未结 3 931
礼貌的吻别
礼貌的吻别 2020-12-15 12:54

Based on my research, this is a very common problem which generally has a fairly simple solution. My task is to alter several queries from get all results into

3条回答
  •  醉酒成梦
    2020-12-15 12:57

    The answer given by @RichardTheKiwi worked great and got me 99% of the way there! I am using MySQL and was only getting the first row of each group marked with a row number, while the rest of the rows remained NULL. This resulted in the query returning only the top hit for each group rather than the first three rows. To fix this, I had to initialize @r in the initvars subquery. I changed,

    from (select @g:=null) initvars

    to

    from (select @g:=null, @r:=null) initvars

    You could also initialize @r to 0 and it would work the same. And for those less familiar with this type of syntax, the additional section is reading through each sorted group and if a row has the same vendorid as the previous row, which is tracked with the @g variable, it increments the row number, which is stored in the variable @r. When this process reaches the next group with a new vendorid, the IF statement will no longer evaluate as true and the @r variable (and thereby the RowNum) will be reset to 1.

提交回复
热议问题