列中的数据而不是行

时间:2014-03-03 23:04:51

标签: sql oracle

我想在程序中显示模块,将程序作为一行显示,而不是为每个程序提供多行模块。

    SELECT program.program_title as program, course_module.title as unit
    FROM program_module
    INNER JOIN program
        ON program_module.program_id = program.id
    INNER JOIN course_module 
        ON program_module.course_module_id = course_module.id

生成: https://dl.dropboxusercontent.com/u/23413810/Stack/current.png

如何让它显示为:https://dl.dropboxusercontent.com/u/23413810/Stack/desired.png

3 个答案:

答案 0 :(得分:2)

如果您想要单独的列,而不是单个以逗号分隔的列,则可以使用数据透视表。从11g开始,有一个内置的枢轴命令;或者你可以用老式的方式做到:

SELECT program,
    MAX(CASE WHEN pos = 1 THEN unit END) AS unit1,
    MAX(CASE WHEN pos = 2 THEN unit END) AS unit2,
    MAX(CASE WHEN pos = 3 THEN unit END) AS unit3,
    MAX(CASE WHEN pos = 4 THEN unit END) AS unit4
FROM (
  SELECT program.id as program_id,
      program.program_title as program,
      course_module.title as unit,
      row_number() over (partition by program.id
          order by course_module.title) as pos
    FROM program_module
    INNER JOIN program
        ON program_module.program_id = program.id
    INNER JOIN course_module 
        ON program_module.course_module_id = course_module.id
)
group by program_id, program
order by program;

无论哪种方式,您都需要知道可以使用多少个模块,并且可以处理所有模块(使用此版本添加更多case语句)。

SQL Fiddle

答案 1 :(得分:1)

你可以这样做:

SELECT program.program_title as program, LISTAGG(course_module.title, ',') WITHIN GROUP (ORDER BY course_module.title) as unit
FROM program_module
INNER JOIN program
    ON program_module.program_id = program.id
INNER JOIN course_module 
    ON program_module.course_module_id = course_module.id
GROUP BY program.program_title

答案 2 :(得分:1)

select p.program_title, 
listagg(m.module_title,',') within group (order by m.module_id) as module_title
from program_module pm
inner join program p on pm.program_id = p.program_id
inner join module m on pm.module_id = m.module_id
group by p.program_title

sqlfiddle here http://sqlfiddle.com/#!4/d3652/5