将2张桌子合并为一张

时间:2019-02-14 22:28:26

标签: sql sql-server

这是一个非常简化的示例,但我希望您能理解。

我们有亲子关系

父母

Id (number)
name

孩子

Parent_id (= id in parent)
Recno
name

父母

1,Alison
2,Mary
3,Helen

孩子

1,1,john
1,2,mike
1,3,fred
2,1,steve
2,2,martin
2,3,sam
3,1,maurice
3,2,pete
3,3,matt

需要将这些表合并在一起并插入到另一个表中

结果

Columns = Id,parent_name,name_1,name_2,name_3
1,Alison,john,mike,fred
2,Mary,steve,martin,sam
3,Helen,maurice,pete,matt

非常感谢收到任何帮助

3 个答案:

答案 0 :(得分:0)

尝试字符串聚合功能STRING_AGG:

SELECT A.Parent_ID, B.parent_name,
    PARSENAME(STRING_AGG(A.name, '.'),1) AS name_1,
    PARSENAME(STRING_AGG(A.name , '.'),2) AS name_2,
    PARSENAME(STRING_AGG(A.name, '.'),3) AS name_3
FROM children A
INNER JOIN parent B ON A.Parent_id = B.Id
GROUP BY A.Parent_ID, B.parent_name

答案 1 :(得分:0)

您可以使用PIVOT

DECLARE @Parent TABLE (Id INT, name VARCHAR(50))
INSERT INTO @Parent
VALUES 
(1,'Alison'),
(2,'Mary'),
(3,'Helen')


DECLARE @Child TABLE (Parent_id INT, Recno INT, name VARCHAR(50))

INSERT INTO @Child VALUES
(1,1,'john'),
(1,2,'mike'),
(1,3,'fred'),
(2,1,'steve'),
(2,2,'martin'),
(2,3,'sam'),
(3,1,'maurice'),
(3,2,'pete'),
(3,3,'matt')

INSERT INTO AnotherTable (Id, parent_name, name_1, name_2, name_3)
SELECT 
    PVT.Id, PVT.parent_name, PVT.[1] name_1, PVT.[2] name_2, PVT.[3] name_3 
FROM 
    ( SELECT P.Id, P.name as parent_name, C.Recno, C.name as child_name FROM @Parent AS P
        INNER JOIN @Child AS C ON P.Id = C.Parent_id ) AS SRC
PIVOT (MAX(SRC.child_name) FOR SRC.Recno IN ([1],[2],[3])) PVT

结果:

Id          name       name_1      name_2    name_3   
----------- ---------- ----------- --------- -----------
1           Alison     john        mike      fred
2           Mary       steve       martin    sam
3           Helen      maurice     pete      matt

答案 2 :(得分:0)

您可以使用通过SELECT查询和PIVOT创建表,如下所示:

CREATE TABLE table_name
   AS 
 (
 SELECT PVT.Id AS ParentId, PVT.name as ParentName, PVT.[1] AS name_1,PVT.[2] AS 
 name_2,PVT.[3] AS name_3 
FROM Parents AS P
INNER JOIN Childs AS C ON P.Id = C.Parent_id
PIVOT (MAX(C.name) FOR C.Recno IN ([1],[2],[3])) PVT
 );