SQL - 选择加入和组

时间:2013-04-25 07:56:49

标签: sql oracle join group-by concatenation

通过连接两个表的SELECT语句的结果如下 -

Col 1   |  Col 2    |  Col 3   |  Col 4
 ----------------------------------
sample11| sample12  | sample13 | sample14
sample11| sample12  | sample23 | sample24
sample11| sample12  | sample23 | sample34
sample11| sample12  | sample43 | sample44

如何对第4行中第2行和第3行的值进行分组和连接(基于第3列中的不同值),以便得到以下结果 -

Col 1   |  Col 2    |  Col 3   |  Col 4
 ----------------------------------
sample11| sample12  | sample13 | sample14
sample11| sample12  | sample23 | sample24, sample34
sample11| sample12  | sample43 | sample44

1 个答案:

答案 0 :(得分:2)

如果您使用的是oracle 11g

SELECT  "Col 1", "Col 2", "Col 3", 
        LISTAGG("Col 4", ',') WITHIN GROUP (ORDER BY "Col 1") AS "Col 4"
FROM    TableName
GROUP   BY "Col 1", "Col 2", "Col 3"