Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

sql - Oracle simple list results to comma separated list with quotes?

I would like to get results of this simple query

select PersonID from Persons where city ='Miami'

as a flat comma separated list with quotes.

desired results should be '3','5','7','8'

http://sqlfiddle.com/#!4/95e86d/1/0

I tried list_add but im getting: ORA-00904: "STRING_AGG": invalid identifier

CREATE TABLE Persons (
    PersonID NUMBER,
    FirstName varchar(255),
    City varchar(255)
);
    
    
      
INSERT INTO Persons (PersonID, FirstName, City)
  VALUES (1, 'Tom B.','Stavanger');
    
INSERT INTO Persons (PersonID, FirstName, City)
  VALUES (2, 'Jerry M.','Train City');
    
INSERT INTO Persons (PersonID, FirstName, City)
  VALUES (3, 'Eric g.','Miami');
      
INSERT INTO Persons (PersonID, FirstName, City)
  VALUES (4, 'Bar Y.','Manhattan');
      
INSERT INTO Persons (PersonID, FirstName, City)
  VALUES (5, 'John K.','Miami');
      
INSERT INTO Persons (PersonID, FirstName, City)
  VALUES (6, 'Foo F.','Washington');
      
INSERT INTO Persons (PersonID, FirstName, City)
  VALUES (7, 'Alen D.','Miami');
      
INSERT INTO Persons (PersonID, FirstName, City)
  VALUES (8, 'John K.','Miami');
question from:https://stackoverflow.com/questions/65923977/oracle-simple-list-results-to-comma-separated-list-with-quotes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
select listagg( '''' || PersonID || '''', ',' ) 
         within group (order by personID) 
  from Persons 
 where city ='Miami'

should work.

I'd have to question why you're trying to produce this particular result. If you're going to generate this string so that you can subsequently use it in the IN list of another dynamically generated SQL statement, you're probably better off taking a step back because there are much better ways to solve the problem.

SQL Fiddle example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...