Search code examples
sqlsql-serversyntaxcode-duplication

Remove code-duplication in SQL query


Is there a way to remove the multiple repetitions of: LEFT([Id], PATINDEX('%[0-9]%', [Id]) - 1) in the following query?

SELECT 
    ISNULL(LEFT([Id], PATINDEX('%[0-9]%', [Id]) - 1), 'Total'), 
    Count([Id]) 
FROM [dbo].[Ids]
GROUP BY ROLLUP(LEFT([Id], PATINDEX('%[0-9]%', [Id]) - 1))
ORDER BY 
    GROUPING(LEFT([Id], PATINDEX('%[0-9]%', [Id]) - 1)), 
    COUNT([Id]) DESC,
    LEFT([Id], PATINDEX('%[0-9]%', [Id]) - 1)

Even though I have a specific exemple I'm hoping to find a generic solution to this problem.


Solution

  • One method uses subqueries. Another CTEs. I like a third way, lateral joins using apply:

    SELECT COALESCE(v.x, 'Total'), 
           Count(*) 
    FROM [dbo].[Ids] i OUTER APPLY
         (VALUES (LEFT([Id], PATINDEX('%[0-9]%', [Id]) - 1) )
         ) v(x)
    GROUP BY ROLLUP(v.x)
    ORDER BY GROUPING(v.x), 2 DESC