有如下表Test
City People Make
广州 1 A
广州 2 B
广州 3 C
上海 4 A
上海 5 E
广州 6 A
上海 7 E
实现如下效果
City People Make
上海 16 AE
广州 12 ABC
在公司论坛看到有人对这个要求的实现,觉得有点复杂。自己研究了下,重新写了下sql如下:
9I(没有环境测试,但是函数在9I中好像都是已经有了的):
WITH TEST AS (SELECT CITY,MAKE,SUM(PEOPLE) PEOPLE FROM Test GROUP BY CITY,MAKE ORDER BY CITY,MAKE)
SELECT CITY,SUM(PEOPLE),(select REVERSE(ltrim(max(sys_connect_by_path(MAKE,',')),',')) MAKE
from
(
SELECT MAKE,CITY,ROWNUM numberid FROM TEST
) T1 WHERE T1.CITY = T2.CITY
start with T.CITY = T2.CITY connect by prior numberid = numberid+1
) MAKE FROM TEST T2 GROUP BY CITY
10G:
WITH TEST AS (SELECT CITY,MAKE,SUM(PEOPLE) PEOPLE FROM Test GROUP BY CITY,MAKE ORDER BY CITY,MAKE)
SELECT CITY,SUM(PEOPLE),WMSYS.WM_CONCAT(MAKE) FROM TEST GROUP BY CITY
==========================================================
相关关键字:
1.sys_connect_by_path 函数主要作用是可以把一个父节点下的所有子节点通过某个字符进行区分
2.start with ... connect by prior ... 递归实现,如
start with pid= 1 connect by prior pid = id
//父id=子id 正树型结构 子id=父id 倒树型结构
上面的SQL中注意
start with T.CITY = T2.CITY connect by prior numberid = numberid+1
与start with T.CITY = T2.CITY connect by prior numberid+1 = numberid的区别
3.REVERSE字符串反转
===========================================================
回顾下其他:
1.Group By, Having, Where, Order by几个语句的执行顺序。一个SQL语句往往会产生多个临时视图,那么这些关键字的执行顺序就非常重要了,因为你必须了解这个关键字是在对应视图形成前的字段进行操作还是对形成的临时视图进行操作,这个问题在使用了别名的视图尤其重要。以上列举的关键字是按照如下顺序进行执行的:Where, Group By, Having, Order by。