Skip to content
Advertisement

dynamic pivot SQL Query in DB2

I have table like below in DB2 where all these 3 columns are VARCHAR data type

I need a dynamic PIVOT query which should select values for ABC_COL1 and ABC_COL2 in row format when FILE_NM filter is used as ABC.TXT

The same query should select the values for XYZ_COL1, XYZ_COL2 and XYZ_COL3 in row format when FILE_NM filter is used as XYZ.TXT

output should be like below when FILE_NM=ABC.TXT

output should be like below when FILE_NM=XYZ.TXT

So, one one query will be able to extract the data. Can any function or equivalent can do the task in this case ?

Advertisement

Answer

You may try the following generic Stored Procedure doing pivoting.

Parameter description:

PARM DESC
sel_stmt Any valid SELECT statement for source data generation
row_cols Comma separated list of column names used in the GROUP BY of final statement
col_col A column name to pivot
agg_col A column name to aggregate
agg_fn Any valid Db2 aggregation function for the column name in “agg_col” parameter
tmp_tbl DGTT name for intermediate result
null_ind Null indicator
rc Return code (OUT)
msg Message text (OUT)
stmt The final SELECT generated (OUT)

Brief description:
DGTT passed in tmp_tbl is created and populated with the result of a SELECT statement passed in sel_stmt. All the column names specified in row_cols, col_col, agg_col must be in the SELECT list of this statement.
The final SELECT statement on this DGTT is dynamically generated using the following rules:

  • for each distinct value Vx in the column name passed in col_col an additional column expression is generated like: , <agg_fn> (case when <col_col> = Vx then <agg_col> end) as "Vx" (, <agg_fn> (case when <col_col> IS NULL then <agg_col> end) as "<null_ind>" is used for Vx IS NULL), where <parameter> means string value passed with this parameter.
  • row_cols column list is used in the GROUP BY, if it’s not NULL.

Use for your case:

1-st call:

DATE_F ROW_ID ABC_COL1 ABC_COL2
20200131 1 123 XYZ
20201231 2 456 XY1

2-nd call:

DATE_F ROW_ID XYZ_COL1 XYZ_COL2 XYZ_COL3
20200630 1 PQR 567 MNO
Advertisement