Search code examples
sqlsql-server-2008common-table-expressioncross-apply

simplify SQL statement by using CTE


I have a query like the following:

SELECT A.a, A.b, B.c,
(CASE WHEN ... THEN ... ELSE ... END) AS CalculatedValue,
B.d
FROM    dbo.TableA A INNER JOIN
        dbo.TableB B ON (...)
WHERE (CASE WHEN ... THEN ... ELSE ... END) BETWEEN @DayStart AND @DayEnd
GROUP BY A.a, (CASE WHEN ... THEN ... ELSE ... END), B.c

to avoid repeating many times the exact same expression: (CASE WHEN ... THEN ... ELSE ... END) I wanted to define a CTE and query such table using in the select, where and group by the expression CalculatedValue

unfortunately this does not work because the select needs to already include the group by when creating the CTE

is there any other way I could use to not repeat the CASE WHEN... so many times?


Solution

  • Use CROSS APPLY, which can be used to define aliased fields and then refer to them:

    SELECT A.a, 
           A.b, 
           B.c,
           CalculatedValue,
           B.d
    FROM    
           dbo.TableA A 
    INNER JOIN
            dbo.TableB B 
            ON (...)
    CROSS APPLY 
            (SELECT (CASE WHEN ... THEN ... ELSE ... END)) CxA(CalculatedValue)
    WHERE CalculatedValue BETWEEN @DayStart AND @DayEnd
    GROUP BY A.a, CalculatedValue, B.c
    

    The CxA is just an alias and you can name it whatever you like.