Es scheint, dass der schnellste Weg, das zu tun, was Sie wollen, darin besteht, Ihren counted2
zu ändern CTE, also die Spalte TimesTested
berücksichtigen Sie Ihre Logik. Also sollte es sein:
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
)