How to return distinct values and their count?

北城以北 提交于 2019-12-24 03:17:07

问题


What I'm trying to do is (hopefully) simple, but I just don't quite have the right syntax. I'd like to return all distinct values in a table with a count of how many records for each value.

So, in PHP, I've got:

$result = mysql_query("SELECT DISTINCT tagName FROM tagTable");
while($row = mysql_fetch_array($result)){
    echo("<p>" . $row['tagName']) . "</p>");
}

This works well. The distinct values are returned! But now how do I get each distinct value's count to display as well? I would want something to the effect of:

echo("<p>" . $row['tagName']) . $tagCountGoesHere . "</p>");

回答1:


You should be able to get that using the GROUP BY clause:

SELECT tagName, count(tagName) AS tagCount FROM tagTable GROUP BY tagName



回答2:


SELECT tagName, count(*) as TagCount 
FROM tagTable 
group by tagname



回答3:


SELECT DISTINCT tagName, COUNT(*) FROM tagTable GROUP BY tagName


来源:https://stackoverflow.com/questions/4348024/how-to-return-distinct-values-and-their-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!