1

Having simple database structure

PERSON_ID   FIRST_NAME  LAST_NAME
1             John          Doe
2             John          Doe
3             Peter       Jackson

need to construct single row output with JSON ARRAY structure containing unique data filtered by first_name,last_name criteria.

Expected outcome:

[{
    "firstname": "John",
    "lastname": "Doe"
},
{
    "firstname": "Peter",
    "lastname": "Jackson"
}] 

Using group by on array level results in two rows

SELECT  json_array(   
                    json_object(  key 'firstname' VALUE t.first_name, 
                                  key 'lastname'  VALUE t.last_name)

                 ) RESPONSEJSON

FROM TESTDATA t
GROUP BY t.first_name, t.last_name



    RESPONSEJSON
1   [{"firstname":"Peter","lastname":"Jackson"}]
2   [{"firstname":"John","lastname":"Doe"}]
0

1 Answer 1

4

Use a subquery to create distinct objects. Then aggregate them together in the array:

create table t (
  person_id int, first_name varchar2(10), last_name varchar2(10)
);

insert into t values (1, 'John', 'Doe' );
insert into t values (2, 'John', 'Doe' );
insert into t values (3, 'Peter', 'Jackson' );
commit;

with jobjs as (
  select  distinct json_object(  
            key 'firstname' VALUE t.first_name, 
            key 'lastname'  VALUE t.last_name
          ) responsejson
  from    t
)
SELECT  json_arrayagg ( responsejson )
FROM    jobjs;

[
  {"firstname":"John","lastname":"Doe"},
  {"firstname":"Peter","lastname":"Jackson"}
]

There's a bug in 12.2 which gives wrong results when using distinct as above. You can get around this with group by instead:

with jobjs as (
  select  json_object(  
            key 'firstname' VALUE t.first_name, 
            key 'lastname'  VALUE t.last_name
          ) responsejson
  from    t
  group   by t.first_name, t.last_name
)
SELECT  json_arrayagg ( responsejson )
FROM    jobjs;

[
  {"firstname":"Peter","lastname":"Jackson"},
  {"firstname":"John","lastname":"Doe"}
]   
Sign up to request clarification or add additional context in comments.

5 Comments

It is a single query?
Sorry, my bad, never used WITH SELECT before. But with your example, the result is: [{"firstname":"John","lastname":"Doe"},{"firstname":"John","lastname":"Doe"},{"firstname":"Peter","lastname":"Jackson"}]
Which version of Oracle Database are you using?
There's a 12.2 bug (fixed in 19c) with distinct; you can use group by instead
12.2, with group by all goes fine. Thanks Chris

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.