'TSQL how to produce UNION result without actual UNION command

Can I produce results like in my example below without actual UNION command. In my real scenario I have 1000 cat(egories) and would like to save typing and learn how to make it smarter without WHERE hard coding. Appreciate your hints, not sure if I can do PIVOT. Thanks M

My setup: SQL Server 2017 (RTM-CU22) My test reproducable test source and sample code which I'd like to modify:

/*  
SELECT * INTO #t  FROM (
SELECT 'A  ' Cat,  101 Score UNION ALL
SELECT 'A  ' Cat,  102 Score UNION ALL
SELECT 'A  ' Cat,  103 Score UNION ALL
SELECT 'BB'  Cat,  2001 Score UNION ALL
SELECT 'BB'  Cat,  2002 Score UNION ALL
SELECT 'CCC' Cat,  3333 Score  
) b           ---      select * from #t
*/


--  this is desired output made with UNION.
SELECT  'A  ' Cat,  COUNT(1)  CCount FROM #t  WHERE Cat = 'A'             UNION
SELECT  'BB ' Cat,  COUNT(1)  CCount FROM #t   WHERE Cat = 'BB'           UNION
SELECT  'CCC' Cat,  COUNT(1)  CCount FROM #t   WHERE Cat NOT IN ('A','BB')

and this is my desired output: enter image description here



Solution 1:[1]

If all you are looking for is a count of each Cat you can do the following:

SELECT Cat, COUNT(*) CCount FROM [#t]
GROUP BY [Cat]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Mylott