I\'m trying to figure out how to write a query that counts values across multiple columns, with the result table having a count in each column for every possible value of an
Maybe something like this:
First some test data:
DECLARE @tbl TABLE(P1 VARCHAR,P2 VARCHAR,P3 VARCHAR)
INSERT INTO @tbl
SELECT 'a','b','a' UNION ALL
SELECT 'a','a','a' UNION ALL
SELECT 'b','b','b' UNION ALL
SELECT 'a','b','b'
Then a pivot like this:
SELECT
*
FROM
(
SELECT 'P1' AS P, P1 AS PValue,P1 AS test FROM @tbl
UNION ALL
SELECT 'P2',P2,P2 FROM @tbl
UNION ALL
SELECT 'P3',P3,P3 FROM @tbl
) AS p
PIVOT
(
COUNT(PValue)
FOR P IN ([P1],[P2],[P3])
) AS pvt
Here is more information about pivot and unpivot