连接三个表以返回单行半逗号分隔

时间:2018-07-25 06:33:25

标签: sql oracle

在这种情况下,我想显示一条记录。

表1

pk,member_id,measure_id

1001,201501,621

4975,201501,525

4997,201501,526

表2

pk,member_id,name,desc

1,201501,Raj,mydesc

表3

pk,measure_id,measure_desc

1,621,measure desc for 621

2,525,measure desc for 525

3,526,measure desc for 526

联接三个表应显示一行这样的记录

member_id,name,desc,all_measure_desc

201501,Raj,mydesc,[measure desc for 621;measure desc for 525;measure desc for 526]

使用SQL查询是否有可能?

1 个答案:

答案 0 :(得分:2)

您可以尝试使用LISTAGG功能。

TestDLL

CREATE TABLE Table1(
   pk INT,
   member_id INT,
   measure_id INT
);


INSERT INTO Table1 VALUES (1001,201501,621);
INSERT INTO Table1 VALUES (4975,201501,525);
INSERT INTO Table1 VALUES (4997,201501,526);

CREATE TABLE Table2( pk INT,member_id INT, name VARCHAR(50),"desc" VARCHAR(50));

INSERT INTO Table2 VALUES (1,201501,'Raj','mydesc');

CREATE TABLE TABLE3(
   pk INT,
   measure_id INT,
   measure_desc VARCHAR(50)
);

INSERT INTO TABLE3 VALUES (1,621,'measure desc for 621');
INSERT INTO TABLE3 VALUES (2,525,'measure desc for 525');
INSERT INTO TABLE3 VALUES (3,526,'measure desc for 526');

查询

SELECT 
    t1.member_id,
    t2.name,
    t2."desc",
    '[' || LISTAGG(t3.measure_desc, ';') WITHIN GROUP (ORDER BY t3.pk) || ']' all_measure_desc
FROM Table1 t1 
INNER JOIN Table2 t2 on t1.member_id = t2.member_id
INNER JOIN Table3 t3 on t1.measure_id = t3.measure_id
GROUP BY  
    t1.member_id,
    t2.name,
    t2."desc"

[结果]

| MEMBER_ID | NAME |   desc |                                                 ALL_MEASURE_DESC |
|-----------|------|--------|------------------------------------------------------------------|
|    201501 |  Raj | mydesc | [measure desc for 621;measure desc for 525;measure desc for 526] |

sqlfiddle