• Take a look at this article:

    Generating n-Tuples with SQL[/url]

    Then look into the discussion thread for a slight performance improvement on the approach:

    http://www.sqlservercentral.com/Forums/Topic1301485-3122-5.aspx

    Coding up the improved approach with your sample data yields this:

    WITH SampleData (Usr, Grp) AS

    (

    SELECT 'SmithA','GrpA'

    UNION ALL SELECT 'SmithA','GrpB'

    UNION ALL SELECT 'MouseM','GrpD'

    UNION ALL SELECT 'MouseM','GrpB'

    UNION ALL SELECT 'MouseM','GrpC'

    ),

    UNIQUEnTuples (n, Usr, Tuples, ID) AS

    (

    SELECT 1, Usr, CAST(Grp AS VARCHAR(8000)), Grp

    FROM SampleData

    UNION ALL

    SELECT 1 + n.n, n.Usr, t.Grp + ',' + n.Tuples, Grp

    FROM UNIQUEnTuples n

    CROSS APPLY

    (

    SELECT Grp

    FROM SampleData t

    WHERE t.Grp < n.ID AND t.Usr = n.Usr

    ) t

    -- WHERE n <= 5

    )

    SELECT *

    FROM UNIQUEnTuples

    ORDER BY Usr, n;

    This has the potential to run like a pig if you really do have 32 groups possible for a Usr. You might be able to improve the performance by running the anchor leg of the query first to a Temp table and then using a WHILE loop to implement the recursive leg.

    If you're not sure how to do this, let me know.

    Edit: I added the commented WHERE clause, because you might want to run it with that WHERE clause uncommented the first time you try with your 32 groups, just to see how long it takes.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St