This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and expected output to sort the IP-Addresses in the correct order.
(Use PARSENAME() for splitting the IP-Addresses into four parts and then get the correct sorted result)
Input Data:
1 2 3 4 5 6 7 8 9 10 11 |
IPAddress --------------- 25.120.144.0 16.16.8.8 116.226.0.1 1.240.255.255 1.0.180.160 122.42.1.10 255.255.16.8 120.140.1.2 1.166.10.44 |
Expected Output:
1 2 3 4 5 6 7 8 9 10 11 |
IPAddress --------------- 1.0.180.160 1.166.10.44 1.240.255.255 16.16.8.8 25.120.144.0 116.226.0.1 120.140.1.2 122.42.1.10 255.255.16.8 |
Create a table with data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
CREATE TABLE NetworkData ( [IPAddress] VARCHAR(15) ) GO INSERT INTO NetworkData VALUES ('25.120.144.0') ,('16.16.8.8') ,('116.226.0.1') ,('1.240.255.255') ,('1.0.180.160') ,('122.42.1.10') ,('255.255.16.8') ,('120.140.1.2') ,('1.166.10.44') GO |
Solution: Using PARSENAME()
1 2 3 4 5 6 |
SELECT [IPAddress] FROM NetworkData ORDER BY CAST(PARSENAME([IPAddress], 4) AS INT) ,CAST(PARSENAME([IPAddress], 3) AS INT) ,CAST(PARSENAME([IPAddress], 2) AS INT) ,CAST(PARSENAME([IPAddress], 1) AS INT) |
Please try the different solution for this puzzle and share it via comment...
Leave a Reply