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
460 views
in Technique[技术] by (71.8m points)

sql - Concat the second column value if the first column value is same

I have a query like below and listed output of it:

SELECT DISTINCT TRACKING_NUM,TITLE_OF_DOC_SEC 
FROM some_table  
WHERE  TRACKING_NUM IS NOT NULL;

o/p:

TRACKING_NUM   TITLE_OF_DOC_SEC
007            Email Flow
007            Test Bug 53306
007            Title 1119
007            Title Test
007            test bug
009            1156
089            Title 21173
098            test Doc Section

I want to re write the query so that get an output to be like this:

TRACKING_NUM    TITLE_OF_DOC_SEC
007             Email Flow,Test Bug 53306,Title 1119,Title Test,test bug
009             1156
089             Title 21173
098             test Doc Section

can anyone help?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you are using Oracle 11g+, then you can use LISTAGG():

SELECT TRACKING_NUM,
  LISTAGG(TITLE_OF_DOC_SEC, ', ') WITHIN GROUP (ORDER BY TRACKING_NUM) AS TITLE_OF_DOC_SEC 
FROM some_table  
WHERE  TRACKING_NUM IS NOT NULL
GROUP BY TRACKING_NUM;

See SQL Fiddle with Demo


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

...