Hi, the following works in MSSQL2000
SELECT tbl.Cust, tbl.Group, tbl.Sales FROM MyTable tbl WHERE (SELECT COUNT(*) FROM MyTable tbl2 WHERE tbl2.Sales > tbl.Sales AND tbl2.Group = tbl.Group AND tbl2.Cust = tbl.Cust) < 2 ORDER BY tbl.Cust ASC, tbl.Group ASC, tbl.Sales DESC
The internal Select Count(*) query works by counting how many records are over the record that he is currently looking at - in this case, you want to have either 0 (1st place) or 1 (2nd place) a place).
Please note that because of this, if you have more than two values ββsharing the first place (for example, 3 A / 1 all with a sales volume of 15), you will get more than two results.
However, for your test suite, it returns the correct results, and using DISTINCT will help if you prefer to get fewer rather than more results in this instance. Also, if there is a separate entry in your entries, this can help you decide between them.
source share