如何在SQL Server树格式表中将子描述添加到父标题

时间:2016-06-12 18:49:28

标签: sql sql-server sql-server-2014

我有一个表,项目标题和描述记录在不同的行中。 我想在项目标题中添加说明。

我目前的表格:

Id        Type      Title                   IdParent
------    ----      -----                   --------
1         itm       LapTop                  null
2         dsc       Dell                    1
3         dsc       1520                    1
4         dsc       15 inches               1 
5         itm       Smart Phone             null
6         dsc       Huawei                  5
7         dsc       P7                      5

和我要求的结果:

id     Description
--     -----------
1      LapTop Dell 1520 15 inches
5      Smart Phone Huawei P7 

获得此结果的适当查询是什么?

1 个答案:

答案 0 :(得分:2)

Declare @Table table (Id int,type varchar(25), title varchar(50),IdParent int)
Insert into @Table (Id,type,title,IdParent) values
(1,'itm','LapTop',null),
(2,'dsc','Dell',1),
(3,'dsc','1520',1),
(4,'dsc','15 inches',1), 
(5,'itm','Smart Phone',null),
(6,'dsc','Huawei',5),
(7,'dsc','P7', 5)

SELECT Id, Description = max(Title)+' ' +STUFF((
    SELECT ' ' + Title FROM @Table
    WHERE IdParent = x.Id 
    FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 2, '')
FROM @Table  AS x
Where IdParent is null
GROUP BY Id

返回

Id  Description
1   LapTop Dell 1520, 15 inches
5   Smart Phone Huawei P7