ORACLE-merge query results

Source: Internet
Author: User
ORACLE-merge query results

Recently, I encountered a problem. I need to combine the values of a certain field in the query results to show that I had a workund und through my own efforts and wrote it down for forgetting.

The following is the form of data in the database. It is queried using common statements as follows:

Select Iq_No, Report_No from Iq_Body

 

Query results:

Iq_No Report_no
--------------------------------------------------
N3200000109042000002 320410109081597
N3200000109042000002 320410109081598
N3200000109042000002 320410109081599
N3200000109042000003 320410109081600
N3200000109042000003 320410109081124

 

Expected results:

Iq_No Report_No
--------------------------------------------
N3200000109042000002 3200000109081597,3200000109081598, 320410109081599
N3200000109042000003 3200000109081600,3200000109081124

 

Use the following SQL statement to obtain the expected result:

SQL statement

1 SELECT IQ_NO,
2 REPLACE (SUBSTR (MAX (CASE
3 WHEN REPORT_NO is not null or length (REPORT_NO) = 0 THEN
4 SYS_CONNECT_BY_PATH (REPORT_NO ,';')
5 END ),
6 2 ),
7 ';',
8 ',') REPORT_NO
9 FROM (SELECT IQ_NO,
10 report_no,
11 RN,
12 lead (RN) over (partition by iq_no order by RN) rn1
13 from (select iq_no,
14 report_no,
15 row_number () over (order by report_no DESC) Rn
16 from iq_body ))
17 start with rn1 is null
18 connect by rn1 = prior Rn
19 group by iq_no
20

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.