Home Forums SQL Server 2008 T-SQL (SS2K8) Is a Dynamic SQL solution possible in this case ? RE: Is a Dynamic SQL solution possible in this case ?

  • Luis Cazares (12/11/2013)


    There's no need to use dynamic code. Here's one option and maybe someone could give a better one because I'm not so sure on its performance with big loads. It's quite simple though. 🙂

    SELECT MYID,

    TITLE

    FROM #Temp

    GROUP BY MYID,

    TITLE

    HAVING COUNT(*) = (SELECT COUNT( DISTINCT ID) FROM #Temp)

    ORDER BY MYID,

    TITLE

    +1

    Unless of course you allow duplicates in your table, like the last row in the following:

    INSERT INTO #Temp

    Select 1, 1, 'First' UNION ALL

    Select 1, 2, 'Second' UNION ALL

    Select 1, 3, 'Third' UNION ALL

    Select 1, 4, 'Fourth' UNION ALL

    Select 1, 5, 'Fifth' UNION ALL

    Select 1, 6, 'Sixth' UNION ALL

    Select 1, 7, 'Seventh' UNION ALL

    Select 1, 8, 'Eighth' UNION ALL

    Select 1, 9, 'Ninth' UNION ALL

    Select 1, 10, 'Tenth' UNION ALL

    Select 2, 3, 'Third' UNION ALL

    Select 2, 4, 'Fourth' UNION ALL

    Select 2, 5, 'Fifth' UNION ALL

    Select 2, 6, 'Sixth' UNION ALL

    Select 2, 7, 'Seventh' UNION ALL

    Select 2, 8, 'Eighth' UNION ALL

    Select 2, 9, 'Ninth' UNION ALL

    Select 3, 1, 'First' UNION ALL

    Select 3, 2, 'Second' UNION ALL

    Select 3, 3, 'Third' UNION ALL

    Select 3, 4, 'Fourth' UNION ALL

    Select 3, 5, 'Fifth' UNION ALL

    Select 3, 6, 'Sixth' UNION ALL

    Select 3, 7, 'Seventh' UNION ALL

    Select 3, 8, 'Eighth' UNION ALL

    Select 3, 8, 'Eighth';

    I believe what Luis has done could be modified for this case, but I'll leave that to you if you say it can happen.


    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