I have a transaction table and I need to group the similar records and for the class column which might be unique, I need to pick the top most value from the lookup table(class table) our of the values for the similar records ( loopup table is ordered based on the priority).
select * from class;
ID NAME
2 BETA
6 OMEGA
5 SIGMA
1 ALPHA1
3 GAMMA
4 DELTA
CREATE OR REPLACE FUNCTION "MIN_VALUE"(classlist array)
RETURNS VARCHAR(200)
LANGUAGE SQL
AS '
select NAME from CLASS
where ID in ( select min(ID) from CLASS
where NAME in (select value from table(flatten(input=>classlist))))
';
select * from T_DATA;
C_ID P_ID D_ID S_ID CLASS
1101111 1404 564 1404 BETA
1101111 1404 599 1425 ALPHA
1101111 1404 564 1404 OMEGA
1101111 1404 564 1425 ALPHA
1101111 1404 564 1404 GAMMA
1101111 1404 564 1425 GAMMA
1101111 1404 599 1425 GAMMA
1101111 1404 564 1425 OMEGA
When I write a query like below it works FINE
select MIN_VALUE(array_construct('OMEGA','GAMMA','BETA'));
When I use it in the actual query it fails with SQL compilation error: Unsupported subquery type cannot be evaluated
select C_ID, P_ID, D_ID, S_ID, MIN_VALUE(class_array) from (
select C_ID, P_ID, D_ID, S_ID, arrayagg(class) class_array
from t_data
group by C_ID,P_ID,D_ID,S_ID
);
OR
select C_ID,P_ID,D_ID,S_ID,MIN_VALUE(ca) from (
select C_ID,P_ID,D_ID,S_ID,array_construct(class_array) ca from (
select C_ID,P_ID,D_ID,S_ID,arrayagg(class) class_array
from t_data
group by C_ID,P_ID,D_ID,S_ID
)
);
I am expecting an output like below from the 8 records above
select C_ID,P_ID,D_ID,S_ID,array_construct(class_array) ca from (
select C_ID,P_ID,D_ID,S_ID,arrayagg(class) class_array
from t_data
group by C_ID,P_ID,D_ID,S_ID
);
Output
C_ID P_ID D_ID S_ID CLASS_ARRAY
1101111 1404 564 1404 ["OMEGA", "GAMMA", "BETA"]
1101111 1404 599 1425 ["ALPHA", "GAMMA"]
1101111 1404 564 1425 ["ALPHA", "GAMMA", "OMEGA"]
When I use the min_value function on the above class_array that will return a single value based on the priority in the lookup table.
C_ID P_ID D_ID S_ID CLASS_ARRAY
1101111 1404 564 1404 BETA
1101111 1404 599 1425 ALPHA
1101111 1404 564 1425 ALPHA
Please suggest some options to figure out why the function runs fine for hardcoded values but fails if the Array is constructed in the query and passed as parameter.