Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query to get count of unique values?

Tags:

database

mysql

Hits Table:

hid | lid | IP
1   | 1   | 123.123.123.123
2   | 1   | 123.123.123.123
3   | 2   | 123.123.123.123
4   | 2   | 123.123.123.123
5   | 2   | 123.123.123.124
6   | 2   | 123.123.123.124
7   | 3   | 123.123.123.124
8   | 3   | 123.123.123.124
9   | 3   | 123.123.123.124

As you can see, there following are the unique hits for the various lid:

lid 1: 1 unique hit
lid 2: 2 unique hits
lid 3: 1 unique hit

So basically, I need a query that will return the following:

lid | uhits |
1   | 1     |
2   | 2     |
3   | 1     |

Anybody know how to get that?

like image 801
coderama Avatar asked May 14 '10 06:05

coderama


People also ask

How do you count unique values in a database?

To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.

Can I use distinct with count?

Yes, you can use COUNT() and DISTINCT together to display the count of only distinct rows. SELECT COUNT(DISTINCT yourColumnName) AS anyVariableName FROM yourTableName; To understand the above syntax, let us create a table.

How do I select distinct and count in SQL?

The correct syntax for using COUNT(DISTINCT) is: SELECT COUNT(DISTINCT Column1) FROM Table; The distinct count will be based off the column in parenthesis. The result set should only be one row, an integer/number of the column you're counting distinct values of.


2 Answers

SELECT lid, COUNT(DISTINCT IP)  
FROM hits  
GROUP BY lid
like image 133
Thea Avatar answered Nov 03 '22 00:11

Thea


Select lid, count(distinct IP) as uhits
from hits
group by lid
like image 37
Lucio M. Tato Avatar answered Nov 02 '22 23:11

Lucio M. Tato