在MySql中按组计算唯一记录

时间:2012-09-26 07:11:41

标签: mysql phpmyadmin

This is my database table, i want to count unique number of visits by user, for example alot 5 person visit 5 times, 20 persons visit 7 times etc

这是我的查询

SELECT count(*) as count 
FROM `tbl_track` 
GROUP BY `user_id`

其结果是(1人访问2次+ 1人访问2次+ 1人访问1次)

Count
2
2
1

我想要一个结果(2人访问2次+ 1人访问1次)

Count
2
1

3 个答案:

答案 0 :(得分:1)

SELECT count(*) as `count`, `visit_times` 
FROM (
  SELECT count(*) as `visit_times` 
  FROM `tbl_track` 
  GROUP BY `user_id`
) AS t GROUP BY `visit_times`

答案 1 :(得分:1)

试试这个:

select cnt as user_count,COUNT(*) as count
from
(
SELECT   COUNT(*) as cnt 
FROM tbl_track 
GROUP BY userid)a
group by cnt


SQL Fiddle demo

答案 2 :(得分:0)

试试这个:

SELECT DISTINCT VisitsCount
FROM
(
    SELECT COUNT(*) AS VisitsCount
    FROM TableName
    GROUP BY UserId
) T