我一直在SQL Server 2008 R2中搜索并尝试不同的查询,但无法获得我正在寻找的结果。这是我对查询的问题。在同一张桌子上我有以下
ObjectID ParentID FlowerID
1 5 100
2 1 100
3 1 105
4 5 103
我正在尝试获取具有多个FlowerID的parentID以显示在下一列上,因此它看起来像这样。
ParentID FlowerID1 FlowerID2
5 100 103
1 100 105
任何人都可以指出我的修正,我也许可以弄清楚其余部分。
谢谢!
答案 0 :(得分:0)
检查一下:
declare @data as table(ObjectID int,ParentID int,FlowerID int)
insert into @data values(1 ,5, 100)
insert into @data values(2 ,1, 100 )
insert into @data values(3 ,1, 105)
insert into @data values(4, 5, 103)
select d1.ParentID,stuff((select ' '+ convert(varchar,d2.FlowerID) from @data d2 where d2.ParentID = d1.ParentID for xml path('')),1,1,'') from @data d1 group by d1.ParentID having count(*) > 1
答案 1 :(得分:0)
这通常使用PIVOT
:
SELECT ParentID, [FlowerID1], [FlowerID2]
FROM
(SELECT ParentID, FlowerID,
'FlowerID' + CAST(ROW_NUMBER() OVER (PARTITION BY ParentID ORDER BY FlowerID) AS VARCHAR(2)) AS FlowerLabel
FROM mytable) AS src
PIVOT
(
MAX(FlowerID)
FOR FlowerLabel IN ([FlowerID1], [FlowerID2] )
) pvt
<强>输出:强>
ParentID FlowerID1 FlowerID2
-----------------------------------
1 100 105
5 100 103