0

我有一个@table包含数据的表变量:

Id Name   Count ParentId
4  Test4  2     1
5  Test5  3     1
6  Test6  2     2
7  Test7  4     2

@table1和一个带有数据的表变量:

Id Name   ParentId
1  Test1  0
2  Test2  0
3  Test3  0
4  Test4  1
5  Test5  1
6  Test6  2
7  Test7  2
8  Test8  3

我想将顶部的 2 个表连接到一个新的表变量,因为@table2 ' Count的数据列等于Count'@table的 总和ParentId。这是@table2连接 2 个表后的数据:

Id Name  Count ParentId
1  Test1 5     0
2  Test2 6     0
3  Test3 0     0
4  Test4 2     1
5  Test5 3     1
6  Test6 2     2
7  Test7 4     2
8  Test8 0     3
4

2 回答 2

1

试试这个

INSERT INTO @table2
SELECT A.Id,
       ISNULL(A.Name,B.Name) AS Name,
       (SELECT COUNT(*) 
        FROM @table A1 LEFT OUTER JOIN @table1 B1 ON A1.Id = B1.id  
        WHERE ISNULL(A1.ParentId,B1.ParentId)= ISNULL(A.ParentId,B.ParentId)) AS count,
        ISNULL(A.ParentId,B.ParentId) AS ParentID
FROM @table A LEFT OUTER JOIN @table1 B 
    ON A.Id = B.id
于 2013-07-24T10:23:31.190 回答
1

试试这个

DECLARE @Table TABLE 
    ([Id] int, [Name] varchar(5), [Count] int, [ParentId] int)

INSERT INTO @Table([Id], [Name], [Count], [ParentId])
VALUES
    (4, 'Test4', 2, 1),
    (5, 'Test5', 3, 1),
    (6, 'Test6', 2, 2),
    (7, 'Test7', 4, 2)

DECLARE @Table1 TABLE ([Id] int, [Name] varchar(5), [ParentId] int)

INSERT INTO @Table1
    ([Id], [Name], [ParentId])
VALUES
    (1, 'Test1', 0),
    (2, 'Test2', 0),
    (3, 'Test3', 0),
    (4, 'Test4', 1),
    (5, 'Test5', 1),
    (6, 'Test6', 2),
    (7, 'Test7', 2),
    (8, 'Test8', 3)

SELECT [Id]
    ,[Name]
    ,SUM([Count]) AS [Count]
    ,[ParentId]
FROM
(
    SELECT T1.[Id]
    , T1.[Name]
    , T1.[ParentId]
    ,ISNULL(CASE WHEN T.[Count] IS NULL 
            THEN (SELECT [Count] FROM @Table TT WHERE TT.Id = T1.ID) 
            ELSE T.[Count] END,0) AS [Count]
    FROM @Table1 T1
    LEFT JOIN @Table T ON T1.[id] = T.[ParentId]
) T
GROUP BY [Id]
, [Name]
, [ParentId]
于 2013-07-24T11:20:43.127 回答