我的MS SQL表中的示例数据
Column Name: IPAddress
1.18.120.201,192.178.120.201
192.168.120.202,192.188.120.202,192.198.120.202
192.168.121.3
192.169.121.50
1.1.1.1
11.11.11.11
作为我想要的输出
192.168
192.169
192.178
192.188
192.198
1.18
1.1
11.11
IPAddress
列也可以有多个IP地址值。
我写了类似下面的内容。请告诉我在查询中需要做出哪些更改
SELECT
SUBSTRING(IPAddress, 1, LEN(IPAddress) - CHARINDEX('.',REVERSE(IPAddress))),
COUNT(*)
FROM
...
GROUP BY
SUBSTRING(IPAddress, 1, LEN(IPAddress) - CHARINDEX('.',REVERSE(IPAddress)))
答案 0 :(得分:0)
在下面试试
;WITH cte(IPAddress)
AS
(
SELECT '1.18.120.201,192.178.120.201' UNION ALL
SELECT '192.168.120.202,192.188.120.202,192.198.120.202' UNION ALL
SELECT '192.168.121.3' UNION ALL
SELECT '192.169.121.50' UNION ALL
SELECT '1.1.1.1' UNION ALL
SELECT '11.11.11.11'
)
SELECT DISTINCT SUBSTRING(IPAddress, 0, CHARINDEX('.', IPAddress, CHARINDEX('.', IPAddress) + 1)) AS IPAddress
FROM (
SELECT Split.a.value('.', 'VARCHAR(1000)') AS IPAddress
FROM (
SELECT CAST('<S>' + REPLACE(IPAddress, ',', '</S><S>') + '</S>' AS XML) AS IPAddress
FROM cte
) AS A
CROSS APPLY IPAddress.nodes('/S') AS Split(a)
) DT
ORDER BY 1 DESC
预期结果
IPAddress
---------
192.198
192.188
192.178
192.169
192.168
11.11
1.18
1.1
答案 1 :(得分:0)
create table #t(IPAddress varchar(15))
insert into #t(IPAddress)
select '192.168.120.201'
union all select '192.178.120.201'
union all select '192.168.120.202'
union all select '192.188.120.202'
union all select '192.198.120.202'
union all select '192.168.121.3'
union all select '192.169.121.50'
select DIstinct parsename(IPAddress,4) +'.'+parsename(IPAddress,3) from #t
答案 2 :(得分:0)
我会使用以下解决方案:
SELECT x.ID, y.XmlCol.value('concat(i[1], ".", i[2])', 'VARCHAR(50)')
FROM (
SELECT ID, CONVERT(XML, '<root><ip><i>' + REPLACE(REPLACE(IP, ',', '</i></ip><ip><i>'), '.', '</i><i>') + '</i></ip></root>') AS IPAsXML
FROM @SourceTable s
) x OUTER APPLY x.IPAsXML.nodes('root/ip') y(XmlCol)
结果:
<强> Demo here 强>