Reputation: 131
I have a list of IDs and IP addresses and I want to display the amount of times an ID is associated with more than 1 IP address.
For example:
Data Set:
ID IP Address
123 1.1.1.1
123 2.2.2.2
456 3.3.3.3
456 4.4.4.4
456 5.5.5.5
Expected Output:
ID Count of Distinct IP addresses
123 2
456 3
How can I accomplish this using SQL?
Thanks in advance!
Upvotes: 2
Views: 3073
Reputation: 11
You can use GROUP BY
like this:
SELECT ID,COUNT(*)
FROM table_name
GROUP BY ID;
Upvotes: 0
Reputation: 76547
Since you are going to be "grouping" these values based on a given column, you can take advantage of SQL's GROUP BY
function that will allow you to create groups on a specific criteria and then perform aggregate operations on those individual groups:
SELECT ID,
COUNT(DISTINCT IpAddress)
FROM YourTable
GROUP BY ID
HAVING COUNT(DISTINCT IpAddress) > 1
The following sections are important:
GROUP BY
- Since you are concerned with "groups" of IP Addresses based on ID, you'll need to separate your individual sets into these groups.COUNT(DISTINCT IpAddress)
- This is important within the context of an individual group, as you'll want to know how many "unique" IP Addresses are present in the group (you can remove the DISTINCT if you don't care about unique results).HAVING
- Since you are dealing with groups / aggregates, you'll need to use HAVING
to indicate which groups to include (i.e. only include groups that have more than one distinct IP Address) Upvotes: 6
Reputation: 31239
You can count distinct ip address by id. Like this:
SELECT ID,COUNT(DISTINCT IPAddress) AS nbr FROM table GROUP BY ID
Update
SELECT ID,COUNT(DISTINCT IPAddress) AS nbr
FROM table
GROUP BY ID
HAVING COUNT(DISTINCT IPAddress) > 1
Upvotes: 2