Question: 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.

Answer: 
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

```
If you do this across multiple queries you could create a [user defined scalar function](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/how-to-use-scalar-valued-user-defined-functions) 

```
CREATE FUNCTION Patterniser(@ID varchar(100))  
RETURNS varchar(100)  
AS  
BEGIN  
   DECLARE @Patterned varchar(100)  
        @Patterned= LEFT(@ID, PATINDEX('%[0-9]%', @ID) - 1)
    RETURN @Patterned
END 

```

Then call `dbo.Patterniser([Id])` wherever you wish to use it