tags:

views:

38

answers:

2

Given the following data:

visit_id
   1
   1
   1
   2
   3
   3
   4
   5

is it possible using only sql (mysql's dialect actually, and no loops in another programming language) to output:

total visits    number of visitor ids
       1             3
       2             1
       3             1

i.e. to break down the data into the number of times they occur? So in the example above, there are 3 visit ids that only occur once (2,4,5), one visit id that occurs twice (3), and one that occurs three times (1).

thanks

+3  A: 

Of course, it's called grouping.

select visit_id, count(visit_id) from visits group by visit_id

František Žiačik
I tried this too, but it seems this is wrong. Notice that "3 => 1" :s
Emil Vikström
yeah, it's not quite right. i think I need to use an sql variable somehow...
Michael Jones
i've edited my question to explain more clearly what i'm trying to achieve.
Michael Jones
why do you want to get 1 when an actual result is 2?
Naktibalda
so i want to know that 3 visitors only came once, 1 person came twice, and one person came 3 times
Michael Jones
Ok. Now the question is clear... :D
Joe
In that case, you need to further group by number of visits, as Mark Baker shown.
František Žiačik
+2  A: 

Building on František's answer

select acc.visitCount as total_visits,
       count(acc.visitCount) as number_of_visitor_ids
  from (
select visit_id, 
       count(visit_id) as visitCount
  from visits 
 group by visit_id
) acc
group by acc.visitCount
Mark Baker
That is correct.
František Žiačik
fantastic, thanks
Michael Jones