GROUP BY or COUNT Like Field Values - UNPIVOT?

前端 未结 4 1922
借酒劲吻你
借酒劲吻你 2021-02-11 03:29

I have a table with test fields, Example

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


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-11 03:51

    Edit: just saw the comment about 7.4, I don't think this will work with that ancient version (unnest() came a lot later). If anyone thinks this is not worth keeping, I'll delete it.

    Taking Erwin's idea to use the "row representation" as a base for the solution a bit further and automatically "normalize" the table on-the-fly:

    select id,
           sum(case when flag = 'F' then 1 else null end) as failed,
           sum(case when flag = 'P' then 1 else null end) as passed,
           sum(case when flag = 'I' then 1 else null end) as incomplete
    from (
      select id, 
             unnest(string_to_array(trim(trailing ')' from substr(all_column_values,strpos(all_column_values, ',') + 1)), ',')) flag
      from (
        SELECT id,
               not_normalized::text AS all_column_values
        FROM not_normalized
      ) t1
    ) t2
    group by id
    

    The heart of the solution is Erwin's trick to make a single value out of the complete row using the cast not_normalized::text. The string functions are applied to strip of the leading id value and the brackets around it.

    The result of that is transformed into an array and that array is transformed into a result set using the unnest() function.

    To understand that part, simply run the inner selects step by step.

    Then the result is grouped and the corresponding values are counted.

提交回复
热议问题