SQL Group By / Count: Count Same Values Across Multiple Columns?

后端 未结 2 1932
Happy的楠姐
Happy的楠姐 2021-01-25 04:33

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

2条回答
  •  野性不改
    2021-01-25 05:17

    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

提交回复
热议问题