SQL count distinct subnets in an IP column

sql, sql-server

Solution

This is not super-efficient, but assuming that the addresses are stored in a varchar column named `IPAddress`, you can do:

SELECT
    SUBSTRING(IPAddress, 1, LEN(IPAddress) - CHARINDEX('.',REVERSE(IPAddress))),
    COUNT(*)
FROM
    ...
GROUP BY
    SUBSTRING(IPAddress, 1, LEN(IPAddress) - CHARINDEX('.',REVERSE(IPAddress)))

This hasn't been tested, so I may be off by one somewhere or missing a parenthesis.

The basic idea is that you want to chop off the end by finding the last dot, and to find the last dot you instead reverse the string and find the first dot, which `CHARINDEX` will do quite easily. To transform the "first dot" position back to the "last dot" position in the original string, you subtract the position from the original length.

(If my assumption is wrong and it's not stored as text, you're unlikely to get a meaningful answer unless you also give the data type.)

Problem

I need to get a get a count of all the distinct subnets in an IP column and group by the subnet on MS SQL. ie.. count all ips that have a subnet of 192.168.0,192.168.1,10.10.10 and so on. Any help is appreciated. Thanks

Original source