我有一张桌子和personidand msgcollums。
personid
msg
personid, msg -------------- 1, 'msg1' 2, 'msg2' 2, 'msg3' 3, 'msg4' 1, 'msg2'
我想得到msg每个的总数personid。我正在尝试以下查询:
select distinct personid, count(*) FROM mytable;
我也试过这个查询
select distinct personid, count(msg) FROM mytable;
但是没有得到实际的结果。我想要以上数据的结果:
id, count -------- 1, 2 2, 2 3, 1
您只需要使用GROUP BY而不是即可DISTINCT。因此,请尝试以下查询:
GROUP BY
DISTINCT
SELECT personid, COUNT(msg) FROM mytable GROUP BY personid ORDER BY personid;
看到这个SQLFiddle
GROUP BY让您使用聚合函数,如AVG(),MAX(),MIN(), SUM(),COUNT()等而DISTINCT只是删除重复。
AVG()
MAX()
MIN()
SUM()
COUNT()