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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is not super-efficient, but assuming that the addresses are stored in a varchar column named
IPAddress, you can do: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
CHARINDEXwill 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.)