开发者

How to return distinct values and their count?

开发者 https://www.devze.com 2023-01-28 01:08 出处:网络
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.

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 distin开发者_StackOverflow社区ct value's count to display as well? I would want something to the effect of:

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


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

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消