我在表格中列出了IP地址以及客户端主机名,使用foriegn密钥字段进行分组,如下所示:
ReqID, Hostname, IPAddress
4, Server01, 192.168.10.5
4, Server02, 192.168.10.6
4, Server10, 192.168.10.7
4, Server15, 192.168.10.8
4, Server18, 192.168.10.9
4, Server23, 192.168.10.10
IP存储为varchars。
我想获得特定ReqID的最高分配IP。我该怎么做?
编辑:我有SQL 2005
答案 0 :(得分:4)
对于SQL Server 2008
SELECT ReqID,
REPLACE(MAX(CAST('/'+ IPAddress +'/' AS HIERARCHYID)).ToString(), '/', '')
FROM your_table
GROUP BY ReqID
对于SQL Server 2005来说,虽然它缺少一个往返回程的函数,却无法想到比@Florin's answer更好的方法。
CREATE FUNCTION [dbo].[ConvertIPToString](@IP bigint)
RETURNS varchar(15)
AS
BEGIN
RETURN (
SELECT LTRIM(I3) + '.'+ LTRIM(J3) + '.' + LTRIM(J2) + '.' + LTRIM(J1)
FROM (SELECT @IP/256, @IP % 256) T1(I1, J1)
CROSS APPLY (SELECT I1/256, I1%256) T2(I2, J2)
CROSS APPLY (SELECT I2/256, I2%256) T3(I3, J3)
)
END
答案 1 :(得分:4)
您可以使用此功能将IP转换为数字:
--Author: Faisal Khan (http://www.stardeveloper.com)
CREATE FUNCTION [dbo].[ConvertIPToLong](@IP varchar(15))
RETURNS bigint
AS
BEGIN
DECLARE @Long bigint
SET @Long = CONVERT(bigint, PARSENAME(@IP, 4)) * 256 * 256 * 256 +
CONVERT(bigint, PARSENAME(@IP, 3)) * 256 * 256 +
CONVERT(bigint, PARSENAME(@IP, 2)) * 256 +
CONVERT(bigint, PARSENAME(@IP, 1))
RETURN (@Long)
END
(来自here)
然后
select reqid, max([dbo].ConvertIPToLong(IPAddress)) as maxIP
from your_table
group by reqID
编辑:在同一来源,您可以使用
-- Author: Faisal Khan (http://www.stardeveloper.com)
CREATE FUNCTION [dbo].[ConvertLongToIP](@Long bigint)
RETURNS varchar(15)
AS
BEGIN
DECLARE @IP varchar(15)
DECLARE @TempLong bigint
DECLARE @Temp bigint
SET @TempLong = @Long
SET @Temp = @TempLong / (256 * 256 * 256)
SET @TempLong = @TempLong - (@Temp * 256 * 256 * 256)
SET @IP = CONVERT(varchar(3), @Temp) + '.'
SET @Temp = @TempLong / (256 * 256)
SET @TempLong = @TempLong - (@Temp * 256 * 256)
SET @IP = @IP + CONVERT(varchar(3), @Temp) + '.'
SET @Temp = @TempLong / 256
SET @TempLong = @TempLong - (@Temp * 256)
SET @IP = @IP + CONVERT(varchar(3), @Temp) + '.'
SET @Temp = @TempLong
SET @TempLong = @TempLong - @Temp
SET @IP = @IP + CONVERT(varchar(3), @Temp)
RETURN (@IP)
END
,查询将是
select reqid, [dbo].ConvertLongToIP(max([dbo].ConvertIPToLong(IPAddress))) as maxIP
from your_table
group by reqID