简体   繁体   中英

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?

Use COUNT(*) and GROUP BY :

SELECT tag_id, COUNT(*) AS total
FROM user_pin_tags
WHERE pin_id =  34
GROUP BY tag_id
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

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

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