Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...