GROUP BY or COUNT Like Field Values - UNPIVOT?

前端 未结 3 947
暗喜
暗喜 2021-02-11 06:50

I have a table with test fields, Example

id         | test1    | test2    | test3    | test4    | test5
+----------+----------+----------+----------+----------+-         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-11 07:32

    I may have come up with a solution:

    SELECT id
          ,l - length(replace(t, 'P', '')) AS nr_p
          ,l - length(replace(t, 'F', '')) AS nr_f
          ,l - length(replace(t, 'I', '')) AS nr_i
    FROM   (SELECT id, test::text AS t, length(test::text) AS l  FROM test) t
    

    The trick works like this:

    • Transform the rowtype into its text representation.
    • Measure character-length.
    • Replace the character you want to count and measure the change in length.
    • Compute the length of the original row in the subselect for repeated use.

    This requires that P, F, I are present nowhere else in the row. Use a sub-select to exclude any other columns that might interfere.

    Tested in 8.4 - 9.1. Nobody uses PostgreSQL 7.4 anymore nowadays, you'll have to test yourself. I only use basic functions, but I am not sure if casting the rowtype to text is feasible in 7.4. If that doesn't work, you'll have to concatenate all test-columns once by hand:

    SELECT id
          ,length(t) - length(replace(t, 'P', '')) AS nr_p
          ,length(t) - length(replace(t, 'F', '')) AS nr_f
          ,length(t) - length(replace(t, 'I', '')) AS nr_i
    FROM   (SELECT id, test1||test2||test3||test4 AS t FROM test) t
    

    This requires all columns to be NOT NULL.

提交回复
热议问题