Get distinct records with counts

若如初见. 提交于 2019-12-10 19:26:42

问题


I have a table with personid and msg colums.

personid, msg
--------------
 1,      'msg1'
 2,      'msg2'
 2,      'msg3'
 3,      'msg4'
 1,      'msg2'

I want to get total msg for each personid. I am trying this query:

select distinct personid, count(*)
FROM mytable;

I also tried this query

select distinct personid, count(msg)
FROM mytable;

But not getting actual result. I want this result for above data:

id, count
--------
1,   2
2,   2
3,   1

回答1:


You just need to use GROUP BY instead of DISTINCT. So try this query:

SELECT personid, COUNT(msg) 
FROM mytable 
GROUP BY personid
ORDER BY personid;

See this SQLFiddle

GROUP BY lets you use aggregate functions, like AVG(), MAX(), MIN(), SUM(), COUNT() etc while DISTINCT just removes duplicates.



来源:https://stackoverflow.com/questions/12330686/get-distinct-records-with-counts

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