Motive
Motive

Reputation: 3111

SQL query for getting count and distinct

I have the following table called user_pin_tags with the following data that I need to query and show distinct tags and a count of each:

| user_id | pin_id | tag_id |
+---------+--------+--------+
    1     |   34   |   7
    2     |   34   |   7
    3     |   34   |   15   
    4     |   34   |   16   
    5     |   34   |   16   
    6     |   34   |   16   

Right now I am using the following query to get the distinct tag_ids

SELECT DISTINCT tag_id
FROM user_pin_tags
WHERE pin_id =  34

which gives the result of:

| tag_id |
+--------+
    7
    15
    16

I need to modify this query to give the distinct tag_ids as well as the count within that pin_id, so I want to generate this result set:

| tag_id | count |
+--------+-------+
    7    |   2
    15   |   1
    16   |   3

How can I modify this query to achieve this?

Upvotes: 2

Views: 86

Answers (3)

d-_-b
d-_-b

Reputation: 23211

SELECT 
   DISTINCT(tag_id)
   ,count(pin_id)
FROM user_pin_tags
WHERE pin_id =  34
GROUP BY tag_id

Group By should do it ... i think.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

Upvotes: 2

Jim
Jim

Reputation: 22656

You can group by the tag_id:

SELECT tag_id, COUNT(pin_id)
FROM user_pin_tags
WHERE pin_id =  34
GROUP BY tag_id

Upvotes: 1

Michael Fredrickson
Michael Fredrickson

Reputation: 37398

Use COUNT(*) and GROUP BY:

SELECT tag_id, COUNT(*) AS total
FROM user_pin_tags
WHERE pin_id =  34
GROUP BY tag_id

Upvotes: 3

Related Questions