• Dave Ballantyne (12/9/2010)


    Tim Widdup (12/9/2010)


    Ok , so how could you achieve this in SQL Server 2000? Again, just need the top x from each group ordered by the ID field.

    Thanks

    You will have to loop or cursor through the data. A "quirky update" may be possible, cant remember if possible in 2000 , sorry.

    Or you can do it with a self-join: http://davidsoussan.co.uk/2009/10/10/how-to-sequence-entries-in-each-sub-set/

    SELECT t1.userid, COUNT(t1.tableid) AS sequence, t1.tableid, t1.tableid >= t2.tableid AS flg

    FROM table t1 INNER JOIN table t2 ON t1.userid = t2.userid

    GROUP BY t1.userid, t1.tableid, flg

    HAVING flg = TRUE

    That method is platform-agnostic so it will work on SQL2000, Access, MySQL, etc. I'd be interested to hear how it compares in performance to the platform-specific row_number(), it runs very efficiently on MySQL and even on Access/JET provided that the join column is properly indexed. You can use any column for the join, or even multiple columns with a multi-colmun index, just so long as it results in a unique index within each subset. Add your condition using the count/sequence number to return the x number of records for each group. My blog shows how to vary the condition and one or two usefull variations and applications of the method.