sql query - how to apply limit within group by

后端 未结 5 1211
生来不讨喜
生来不讨喜 2020-12-09 17:03

I have a table named t1 with following fields: ROWID, CID, PID, Score, SortKey

it has the following data:

1, C1, P1, 10, 1
2, C1, P2, 20, 2
3, C1, P3         


        
5条回答
  •  长情又很酷
    2020-12-09 18:02

    This is not actually a GROUP BY problem (you're not aggregating values). This is a greatest-n-per-group problem (I think there's actually a greatest-n-per-group tag here at Stackoverflow).

    The exact details of a solution will depend on issues such as whether you ever have the same sort key twice per group. You can start with something like this:

    SELECT * FROM table T1 WHERE Score > 20 AND
      (SELECT COUNT(*) FROM table T2 
          WHERE T2.CID = T1.CID AND T2.SortKey <= T1.SortKey AND T2.RowID <> T1.RowID
            AND T1.Score > 20) < 2;
      ORDER BY CID, SortKey;
    

    What this does is consider only those rows with scores above 20. Then, for each candidate row it counts the number of other rows in the same table that have scores > 20 but sortkeys less than or equal to this row's sortkey. If that number is 0 or 1 row, then this row qualifies for inclusion in the results.

    Finally ORDER by performs your sort.

提交回复
热议问题