从两个不同的行记录

时间:2017-11-21 09:48:56

标签: sql oracle

我的Oracle数据库中有以下行记录

TERM    CRN   SUBJ    CRSE    SCHD_CODE
2016    104   BIOL     252        B
2016    104   BIOL     252        L
2017    123   MATH     201        E
2017    123   MATH     201        S

是否有可能使用group by生成一个SQL语句以在“SCHD_CODE”字段上提供串联,如下所示???

Select term, CRN, SUBJ, CRSE, (SCH_CODE||'/'|| SCH_CODE) from xx 
GROUP BY term, CRN, SUBJ, CRSE

需要低于所需的输出:

TERM       CRN     SUBJ    CRSE   SCHD_CODE
2016       104     BIOL     252     B/L
2017       123     MATH     201     E/S

3 个答案:

答案 0 :(得分:3)

使用LISTAGG

SELECT term,
       CRN,
       SUBJ,
       CRSE,
       LISTAGG(SCHD_CODE, '/' ) WITHIN GROUP ( ORDER BY schd_code ) AS schd_code
FROM   xx 
GROUP BY term, CRN, SUBJ, CRSE

答案 1 :(得分:0)

如果仅需要CONCAT 2行,则只需使用MINMAX

试试这个,

Select term, CRN, SUBJ, CRSE
    ,(MIN(SCH_CODE)||'/'|| MAX(SCH_CODE)) from xx 
GROUP BY term, CRN, SUBJ, CRSE

答案 2 :(得分:0)

您也可以尝试自我加入:

select * from (
    select 
    case when table1.SCHD_CODE <> table2.SCHD_CODE then "" else NULL END as test,
    table1.TERM,table1.SUBJRN,table1.SUBJ,table1.CRSE,table1.SCHD_CODE, (table1.SCHD_CODE||'/'||table2.SCHD_CODE)
    from result table1
    join result table2 on table1.TERM=table2.TERM
    and table1.SUBJRN=table2.SUBJRN 
    and table1.SUBJ=table2.SUBJ
    and table1.CRSE=table2.CRSE) b where test is not null