我有一张table叫 dbo.WebsiteIP
有两列的 IPAddress
, SiteName
,我正在做一个大容量的插入值到这个表中,如下所示
IPAddress SiteName
192.168.30.6 website1.domain.com
192.168.30.6 website2.domain.com
192.168.30.7 website3.domain.com
192.168.30.7 website4.domain.com
192.168.30.7 website5.domain.com
192.168.30.7 website6.domain.com
192.168.30.7 website7.domain.com
192.168.30.8 website8.domain.com
192.168.30.8 website9.domain.com
192.168.30.8 website10.domain.com
192.168.30.8 website11.domain.com
192.168.30.9 website12.domain.com
192.168.30.8 website13.domain.com
192.168.30.8 website14.domain.com
192.168.30.24 website15.domain.com
192.168.30.8 website16.domain.com
192.168.30.8 website17.domain.com
我想对ip地址做一个独特的查询,并将 SiteName
就像下面一样
IPAddress WebsiteName
192.168.30.6 website1, website2,
192.168.30.7 website3, website4, website5, website6, website7
192.168.30.8 website8, website9, website10, website11, website13, website14
192.168.30.9 website12
192.168.30.24 website15
我能把 IPAddress
使用下面的查询但是如何组合适当的 Sitename
到ip地址。
Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO
4条答案
按热度按时间vtwuwzda1#
正确的答案是修复数据模型。
为了得到想要的结果,你可以
在线演示
hfyxw5xn2#
您可以通过使用
STUFF
```DECLARE @T Table(
IP VARCHAR(MAX),
WEBSITE VARCHAR(MAX))
INSERT INTO @T VALUES('192.168.30.6','website1.domain.com')
INSERT INTO @T VALUES('192.168.30.6','website2.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website3.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website4.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website5.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website6.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website7.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website8.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website9.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website10.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website11.domain.com')
INSERT INTO @T VALUES('192.168.30.9','website12.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website13.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website14.domain.com')
INSERT INTO @T VALUES('192.168.30.24','website15.domain.com')
INSERT INTO @T VALUES('192.168.30.8',' website16.domain.com')
INSERT INTO @T VALUES('192.168.30.8',' website17.domain.com')
SELECT M.IP,STUFF (( Select ','+WEBSITE
From @T S WHERE S.IP=M.IP
FOR XML PATH('')),1,1,'')
FROM @T M GROUP BY M.IP
update Table1 T1 set IP = T2.SiteName
from(SELECT M.IP,STUFF (( Select ','+WEBSITE
From @T S WHERE S.IP=M.IP
FOR XML PATH('')),1,1,'') AS Site
FROM @T M GROUP BY M.IP
) S ON S.IP=T1.IP
uajslkp63#
请使用下面的查询,
v8wbuo2f4#
使用材料的建议是一个很好的解决办法。如果您的版本是sql server 2017或更高版本,则可以使用更简单的de function string\ u agg语法。