I'm currently running a query that is supposed to return a salesperson's aggregated revenue, grouped by individual clients.
Because of how user input was handled, there are a lot of near-duplicate rows with minor mispellings/additions to client names. As you can see in the code below, I'm trying to trim off one of the problem strings in order to prevent duplicate rows for the same clients.
However, though the CASE statement successfully removes "@iraPrefix", the rows with now-identical client names are still not grouped together because their revenue fields are not being summed.
How should I approach this?
DECLARE @iraPrefix VARCHAR(7)
DECLARE @iraLen INT
SET @iraPrefix = 'FOO BAR '
SET @iraLen = LEN(@iraPrefix)
SELECT [client] = (
CASE SUBSTRING([name], 1, @iraLen)
WHEN @iraPrefix THEN SUBSTRING([name], @iraLen+2, (LEN([name]) - @iraLen))
ELSE [name]
END
)
, CONCAT( sal.firstname
, ' '
, sal.lastname) AS [salesman]
, [revenue] = SUM(net)
Here's an example of the query results without prefix removal:
An example of the current query results:
And an example of the results I want:
Best Answer
Just aggregate one more time.
You can do this by
SELECT ... INTO #intermediate FROM...
) and then aggregating the cached intermediate resultsSELECT
ing against whatever alias you assign to it.See this fiddle for an example. But for verbosity's sake, assuming your data is all stored in a table called
barfoo
, then one way you could do this using a Common Table Expression (or CTE) is...