简体   繁体   中英

SQL: Count the number of unique occurrences?

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!

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 (ie only include groups that have more than one distinct IP Address)

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

You can use GROUP BY like this:

SELECT ID,COUNT(*)
FROM table_name
GROUP BY ID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM