有两个表..按一些值分组..然后加入它们

时间:2014-04-24 22:25:05

标签: sql oracle

我有 table1

id1 name1 address1
1    abc  add1
2    abc  add2

表2

id2 name2 mother_name
1    abc   iii
2    abc   jjj

我想要类似的东西:

id1    name1  addr1       name2  xmlagg
1,2    abc    add1,add2   abc    iii,jjj `

我需要写什么查询?因此它按 name1 进行分组,然后按 name2 进行分组并加入它们。

2 个答案:

答案 0 :(得分:0)

这是你想要的吗?

select id1, name1, addr1, name2, xmlagg
from (select name1, listagg(id1, ',') within group (order by id1) as id1,
             listagg(addr1, ',') within group (order by addr1) as addr1
      from table1
      group by name1
     ) t1 join
     (select name2, listagg(id2, ',') within group (order by id2) as id2
             listagg(mother_name, ',') within group (order by mother_name) as xmlagg
      from table2
      group by name2
     ) t2
     on t1.id1 = t2.id2;

这假设您加入了ID列表。

答案 1 :(得分:0)

CREATE TABLE [dbo].[test2](
  [id2] [int] NULL,
  [name2] [varchar](10) NULL,
  [mother_name] [varchar](10) NULL
)
GO
INSERT [dbo].[test2] ([id2], [name2], [mother_name]) VALUES (1, N'abc', N'iii')
INSERT [dbo].[test2] ([id2], [name2], [mother_name]) VALUES (2, N'abc', N'jjj')

GO
CREATE TABLE [dbo].[test1](
  [id1] [int] NULL,
  [name1] [varchar](10) NULL,
  [address1] [varchar](10) NULL
)
GO
INSERT [dbo].[test1] ([id1], [name1], [address1]) VALUES (1, N'abc', N'add1')
INSERT [dbo].[test1] ([id1], [name1], [address1]) VALUES (2, N'abc', N'add2')
-----------------

---With CTE , STUFF AND COAESCE FUNCTION it is easy to denormalize  :
;WITH CTE AS ( SELECT * FROM TEST1 T1 JOIN TEST2 T2  ON T1.NAME1=T2.NAME2)


SELECT COALESCE(STUFF(( select DISTINCT  ','+CAST (ID1 AS VARCHAR) FROM CTE  WHERE ID1=CTE.ID1  ORDER BY ','+CAST (ID1 AS VARCHAR) FOR XML PATH(''),
   TYPE).value('.','varchar(max)'),1,1,''), '') AS ID1 , NAME1,
COALESCE(STUFF(( select DISTINCT ','+ADDRESS1  FROM CTE  WHERE ID1=CTE.ID1  ORDER BY ','+ADDRESS1 FOR XML PATH(''),
    TYPE).value('.','varchar(max)'),1,1,''), '') AS ADD1,NAME2,
COALESCE(STUFF(( select DISTINCT ','+MOTHER_NAME FROM CTE  WHERE ID1=CTE.ID1  ORDER BY ','+MOTHER_NAME FOR XML PATH(''),
    TYPE).value('.','varchar(max)'),1,1,''), '') AS XMLAGG

FROM CTE

输出如下:

ID1  NAME1  ADD1         NAME2    XMLAGG!
1,2  abc  add1,add2  abc  iii,jjj
1,2  abc  add1,add2  abc  iii,jjj
1,2  abc  add1,add2  abc  iii,jjj
1,2  abc  add1,add2  abc  iii,jjj

enter image description here