0

I have a subquery in my SELECT statement that returns more than one row, but I need both values. Is there anyway to concatenate the multiple values with a comma to make the outside query think the subquery is only returning one value?

Example of my query:

select o.id,
   (select v.value v from values v join attributes a on v.att_id=a.att_id where a.att_id='100' and v.id=o.id)
from objects o
where o.class_id='GGzX';

Thanks in advance!

Brandon Lehman
  • 69
  • 1
  • 1
  • 7

3 Answers3

3

Try with this query, maybe will be useful (click here to test the query):

CREATE TABLE TEST1(
ID INT);

CREATE TABLE TEST2(
    ID INT,
    TXT VARCHAR2(100));

INSERT INTO TEST1 VALUES(1);
INSERT INTO TEST1 VALUES(2);
INSERT INTO TEST1 VALUES(3);

INSERT INTO TEST2 VALUES(1,'A');
INSERT INTO TEST2 VALUES(1,'B');
INSERT INTO TEST2 VALUES(2,'C');
INSERT INTO TEST2 VALUES(3,'A');
INSERT INTO TEST2 VALUES(3,'B');
INSERT INTO TEST2 VALUES(3,'C');

/* HERE IS THE QUERY!!!*/
SELECT A.ID, 
(SELECT listagg(B.TXT,',' ) WITHIN GROUP (ORDER BY B.ID)
FROM TEST2 B WHERE B.ID = A.ID
) AS CONTATENATED_FIELD
FROM TEST1 A;

NOTE: listagg works in 11.X versions, please see this link for more information.

According with your query maybe you need something like this:

select o.id,
(SELECT listagg(v.value,',' ) WITHIN GROUP (ORDER BY v.value) from values v join attributes a on v.att_id=a.att_id where a.att_id='100' and v.id=o.id)
from objects o
where o.class_id='GGzX';
Gaston Flores
  • 2,457
  • 3
  • 23
  • 42
0

Just add the GROUP BY a.att_id or limit your query

select o.id,
   (select v.value val from values v join attributes a on v.att_id=a.att_id
 where a.att_id='100' and v.id=o.id GROUP BY a.att_id)
from objects o
where o.class_id='GGzX';

OR


select o.id,
   (select v.value val from values v join attributes a on v.att_id=a.att_id
 where a.att_id='100' and v.id=o.id LIMIT 1)
from objects o
where o.class_id='GGzX';

OR just group the values by any seperator

select o.id,
   (select group_concat( v.value SEPARATOR ' / ') val from values v join attributes a on v.att_id=a.att_id
 where a.att_id='100' and v.id=o.id GROUP BY a.att_id)
from objects o
where o.class_id='GGzX';
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118