2012-09-08 58 views
3

我有一個表personidmsg列。獲取不同的記錄與計數

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 

回答

5

你只需要使用GROUP BY,而不是DISTINCT。因此,嘗試此查詢:

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

See this SQLFiddle

GROUP BY讓您使用聚合函數,如AVG()MAX()MIN()SUM()COUNT()等而DISTINCT只是刪除重複。

+0

非常感謝hims056 – Pankaj

+1

@Downvoter,小心點評? – hims056