多行变一行 数据合并SQL

SELECT    n_sec_code, TRANSLATE (LTRIM (text, '/'), '*/', '*,') researcherList
     FROM (SELECT ROW_NUMBER () OVER (PARTITION BY n_sec_code ORDER BY n_sec_code,
                   lvl DESC) rn,
                  n_sec_code, text
             FROM (SELECT      n_sec_code, LEVEL lvl,
                              SYS_CONNECT_BY_PATH (c_researcher_code,'/') text
                         FROM (SELECT    n_sec_code, c_researcher_code as c_researcher_code,
                                        ROW_NUMBER () OVER (PARTITION BY n_sec_code ORDER BY n_sec_code,c_researcher_code) x
                                   FROM m_researcher_stock_rel
                               ORDER BY n_sec_code, c_researcher_code) a
                   CONNECT BY n_sec_code = PRIOR n_sec_code AND x - 1 = PRIOR x))
    WHERE rn = 1
ORDER BY n_sec_code;

预想的结果成功出现,多行数据成功汇总到一行,特此分享与大家。对于你自己的应用中,只需要把SQL中“n_sec_code”

换为你的用来汇总的列,“c_researcher_code”替换为需合并文本的列,“m_researcher_stock_rel”替换为你的表名,就是这么简单。

SQL分析:

1、利用 “ROW_NUMBER () OVER (PARTITION BY……” 为按“股票代码”汇总后的数据行添加组内序号

2、“SYS_CONNECT_BY_PATH” 按组内序号相邻关系,为每一层进行不同行的“研究员代码”叠加

3、再次利用“股票代码”进行组内分组,但按第二部中的层次排倒序,增加调整后等级

4、取所有调整后等级为1的结果,即为所要求的数据行

方法很巧妙,值得学习。:-)




又一个示例:

WITH tab AS(
select '01' no,'ss' name, 10 jiner,'麦子' you from dual union all
select '02' no,'dd' name, 11 jiner,'萝卜' you from dual union all
select '03' no,'cc' name, 9 jiner,'大豆' you from dual union all
select '01' no,'ss' name, 10 jiner,'白菜' you from dual)
SELECT a.no, a.name, a.jiner, ltrim(MAX(sys_connect_by_path(you, ',')), ',') you
FROM (SELECT row_number() over(PARTITION BY a.no, a.name, a.jiner
         ORDER BY a.no, a.name, a.jiner) rn,a.*
          FROM tab a) a
START WITH rn = 1
CONNECT BY PRIOR rn = rn - 1 AND
           a.no = PRIOR a.no AND
           a.name = PRIOR a.name AND
           a.jiner = PRIOR a.jiner
GROUP BY a.no, a.name, a.jiner

你可能感兴趣的:(多行变一行 数据合并SQL)