Skip to content
Advertisement

Pivot row values matching a pattern into column names

I have data that look like this:

I would like to pivot these data so that for each set of rows with the same OH_IDNR and with the same common/non-unique part of OCV_VNAME, these columns are returned:

  1. OH_IDNR
  2. The common part of OCV_VNAME (e.g., ‘response_part_0_script_0_’)
  3. – n. One column for each unique part of OCV_Name (e.g.,’ resourceName’), with OCV_VALUE as the value.

E.g.,

This obviously assumes that the unique part of OCV_VNAME is a string suitable for use as a column name. I’ve tried a few things, but the elegant solution eludes me.

Advertisement

Answer

You can do conditional aggregation:

Demo on DB Fiddle:

OH_IDNR | OCV_VNAME_COMMON          | CODE_0           | QUERYTYPE | RESOURCENAME         | SAVETO   | USEARRAY
------: | :------------------------ | :--------------- | :-------- | :------------------- | :------- | :-------
8420518 | response_part_0_script_0_ | $[*].id          | JSONPath  | profileIds#          | variable | TRUE    
8420518 | response_part_0_script_1_ | $[*].name        | JSONPath  | profileNames#        | variable | TRUE    
8420518 | response_part_0_script_2_ | $[*].environment | JSONPath  | profileEnvironments# | variable | TRUE    
8420518 | response_part_0_script_3_ | $[*].description | JSONPath  | profileDescriptions# | variable | TRUE    

You might find it more readable to parse in a subquery first:

Demo on DB Fiddle

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement