我有一个包含数据的表变量@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
的{{1}}与@table
相同的总和。加入2个表后,这是ParentId
个数据:
@table2
答案 0 :(得分: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
答案 1 :(得分: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]