使用SQL在单个字段记录中附加多个记录的数据

时间:2016-02-02 04:23:48

标签: sql oracle

假设我有一张表格如下

--------------------------
Name  |  Subject  |  Marks
--------------------------
Jon   |  Maths    |  80
--------------------------
Rob   |  Biology  |  90
--------------------------

我希望输出为

Jon,Maths,80,Rob,Biology,90

我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:1)

尝试这种方式:

SELECT listagg (jColumn , ',')
    WITHIN GROUP (ORDER BY jColumn) enames
FROM (SELECT TOP 5 name + ',' + subject + ',' + Marks as jColumn 
      FROM emp) a
GROUP BY jColumn 

答案 1 :(得分:1)

你需要这样的东西。

SELECT listagg(csv,',') within
GROUP (
     ORDER BY constant_no) derived_string
FROM
(SELECT 1 AS constant_no,
        name||','||subject||','||to_char(Marks) AS csv
 FROM tbl
 WHERE rownum<6)
GROUP BY constant_no

这里首先我连接3列,并在从表中仅选择5行后为每一行分配一个常量。然后我再次将此派生表用于listagg以获得所需的输出。

因此,此查询将生成如下表

SELECT 1 AS constant_no,
            name||','||subject||','||to_char(Marks) AS csv
     FROM tbl
     WHERE rownum<6 

派生表输出

+-------------+-------------------+
| CONSTANT_NO |       CSV         |
+-------------+-------------------+
|           1 | Jon,Maths,80      |
|           1 | Rob,Biology,90    |
|           1 | Utsav,Maths,60    |
|           1 | Suresh,Biology,95 |
|           1 | Tim,Maths,40      |
+-------------+-------------------+

现在您可以在listagg函数中使用它。

如果您要测试

,这是完整的查询
with tbl(Name, Subject, Marks) as (
select 'Jon', 'Maths', 80 from dual union all
select 'Rob', 'Biology', 90 from dual union all
select 'Utsav', 'Maths', 60 from dual union all
select 'Suresh', 'Biology', 95 from dual union all
select 'Tim', 'Maths', 40 from dual union all
select 'Ramesh', 'Maths', 80 from dual
)
SELECT listagg(csv,',') within
GROUP (
     ORDER BY constant_no) derived_string
FROM
(SELECT 1 AS constant_no,
        name||','||subject||','||to_char(Marks) AS csv
 FROM tbl
 WHERE rownum<6)
GROUP BY constant_no

输出

Jon,Maths,80,Rob,Biology,90,Suresh,Biology,95,Tim,Maths,40,Utsav,Maths,60

注意:输出是随机的5行。除非您有确定顺序的密钥,否则oracle不一定会按任何特定顺序返回行。