Oracle查询结果列转行 痛定思痛。 2023-02-18 14:30 5阅读 0赞 > 有个结果集有多列、多行,需要将某几列合并为行,可使用listagg函数实现。 **有个结果集是多行多列的:** <table> <thead> <tr> <th>主键ID</th> <th>编号</th> <th>体积</th> <th>长</th> <th>宽</th> <th>高</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>001</td> <td>24</td> <td>2cm</td> <td>3cm</td> <td>4cm</td> </tr> <tr> <td>2</td> <td>001</td> <td>60</td> <td>3cm</td> <td>4cm</td> <td>5cm</td> </tr> <tr> <td>3</td> <td>002</td> <td>120</td> <td>4cm</td> <td>5cm</td> <td>6cm</td> </tr> <tr> <td>4</td> <td>002</td> <td>210</td> <td>5cm</td> <td>6cm</td> <td>7cm</td> </tr> <tr> <td>5</td> <td>003</td> <td>504</td> <td>6cm</td> <td>7cm</td> <td>8cm</td> </tr> </tbody> </table> **想要实现的效果:将编号一致的结果行的数据,进行汇总,显示为1列** <table> <thead> <tr> <th>编号</th> <th>列转行效果</th> </tr> </thead> <tbody> <tr> <td>001</td> <td>24,2cm<em>3cm</em>4cm;60,3cm<em>4cm</em>5cm;</td> </tr> <tr> <td>002</td> <td>120,4cm<em>5cm</em>6cm;210,5cm<em>6cm</em>7cm;</td> </tr> <tr> <td>003</td> <td>504,6cm<em>7cm</em>8cm</td> </tr> </tbody> </table> **实现sql:** LISTAGG(NAME2,NAME3) WITHIN GROUP(ORDER BY NULL) --name2,字段 --列传行后的分割符号,如,;-等 --order by 字段,name3,也可以为null select id,listagg(t.volume || ','||t.length ||'cm*'|| t.width ||'cm*' ||t.height ||'cm;',';') within group (order by null) from tablexx t where t.grid_id_name='dataGridViewEx1' and t.rpt_id='154947' group by rpt_id
还没有评论,来说两句吧...