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

@table2 上の 2 つのテーブルを新しいテーブル変数に結合し たいCountのは、データの列が同じの 合計に等しいからです。そして、これは2つのテーブルを結合した後のデータです:Count@tableParentId@table2

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 に答える