问题:
员工表: A(E_ID,NAME,) 部门表: B(D_ID,D_NAME) 员工与部门关系:C(ID,E_ID,D_ID)
SELECT A.E_ID,A.NAME ,B.D_NAME FROM A INNER JOIN C ON A.E_ID=C.E_ID INNER JOIN B ON B.D_ID=C.D_ID;
这样查处的记录会出现,
1,张三,研发部
1,张三,市场部
2,李四,销售部
我想查询结果显示成这样:
1,张三,研发部|市场部 2,李四,销售部 3 ...
SQL 怎么写?
解:
方法1
SELECT A.E_ID, A.NAME, REPLACE(WM_CONCAT(B.D_NAME), ',', '|') D_NAME FROM A INNER JOIN C ON A.E_ID = C.E_ID INNER JOIN B ON B.D_ID = C.D_ID GROUP BY A.E_ID, A.NAME
方法2:
SELECT A.E_ID, A.NAME, listagg(B.D_NAME,',') within GROUP (ORDER BY B.D_NAME)D_NAME FROM A INNER JOIN C ON A.E_ID = C.E_ID INNER JOIN B ON B.D_ID = C.D_ID GROUP BY A.E_ID, A.NAME