Wygląda na to, że najszybszym sposobem na zrobienie tego, co chcesz, jest zmiana counted2
CTE, więc kolumna TimesTested
weź pod uwagę swoją logikę. A więc powinno być:
counted2 as (
SELECT
client_id,
CASE WHEN TimesTested >= 12 THEN 12 ELSE TimesTested END TimesTested,
CAST(COUNT(*) AS varchar(30)) AS count,
CAST(AVG(testfreq) as varchar(30)) as TestFreq,
CAST(STDEV(TestFreq) as varchar(30)) Stdv
FROM counted
GROUP BY
client_id,
CASE WHEN TimesTested >= 12 THEN 12 ELSE TimesTested END
)