Home Forums SQL Server 2008 T-SQL (SS2K8) Converting table-value function to set based query RE: Converting table-value function to set based query

  • This seems to work as desired.

    WITH Scores AS(

    SELECT EVL.Account,

    EVL.Ident1,

    EVL.EvalDate,

    FIL.Module_ID,

    AVG(CASE WHEN ANSWER_VALUE IN (0,1,2,3) THEN ANSWER_VALUE*1.0 ELSE NULL END)*10.0 AS Score,

    DENSE_RANK() OVER(ORDER BY EVL.Ident1 DESC) ranking

    FROM #evalanswers AS ANS

    JOIN #filter AS FIL ON ANS.Answer_ID = FIL.Answer_ID

    JOIN #evaluations EVL ON EVL.Ident1 = ANS.Ident1

    WHERE ANS.Answer_Value IN (-1,0,1,2,3)

    AND EVL.COMPLETE = 1

    GROUP BY EVL.Account,

    EVL.Ident1,

    EVL.EvalDate,

    FIL.Module_ID

    )

    SELECT s2.Account,

    s2.Module_ID,

    MAX( s2.Ident1) AS IdTime2,

    MAX( s1.Ident1) AS IdTime1,

    s2.EvalDate,

    MAX( s1.Score) AS Score1,

    MAX( s2.Score) AS Score2

    FROM Scores s1

    JOIN Scores s2 ON s1.ranking = s2.ranking + 1

    AND s1.Module_ID = s2.Module_ID

    AND s1.Account = s2.Account

    GROUP BY s2.Account, s2.EvalDate, s2.Module_ID

    ORDER BY IdTime2 DESC

    To clarify, I'm getting the scores (with the formula) before the JOIN. That way, you won't loose rows in your calculation. Using a self-join of the calculated recordset, you can have 2 scores compared at a time with infinite possible rows. The DENSE_RANK() function is to have a value to join with the previous evaluation.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2