请教一条SQL语句(查询,嵌套)
现有主表Table1,副表Table2。
(表结构和SQL语句等经过极度简化,只是为了描述问题)
Table1表结构如下:
ManageNo 主键,
UserName, (人名)
UserGroup(所属小组)
Table2表结构如下:
ManageNo 主键,(与Table1关联)
SequenceNo 主键,(从1到99的编号)
FavoriteFood(爱吃的食物)
以上所有项目类型皆为字符。
主表的每条数据,在副表中可能有n条对应的数据。(n可能为0)
(每个人可能有多种爱吃的食物,也可能没有)
需求:
检索UserGroup为 "A "的所有数据,
表中现有如下数据:
Table1的内容:
ManageNo UserName UserGroup
"M001 " "张三 " "A "
"M002 " "李四 " "A "
"M003 " "王五 " "A "
Table2的内容:
ManageNo SequenceNo FavoriteFood
"M001 " "01 " "红苹果 "
"M001 " "02 " "绿苹果 "
"M001 " "03 " "蓝苹果 "
"M002 " "01 " "炸猪排 "
"M002 " "02 " "炸鸡排 "
要求结果格式如下:
ManageNo UserName FavoriteFood
"M001 " "张三 " "红苹果,绿苹果,蓝苹果 "
"M002 " "李四 " "炸猪排,炸鸡排 "
"M003 " "王五 " " "
我设想的SQL如下:
SELECT UNIQUE
T1.ManageNo AS ManageNo,
NVL((SELECT
MAX(FavoriteFood) as FavoriteFood
FROM
(SELECT
LTRIM(SYS_CONNECT_BY_PATH(FavoriteFood, ', '), ', ') FavoriteFood
FROM
(SELECT
T2.FavoriteFood as FavoriteFood,
ROWNUM as RN