SQL:从表中逐步计算唯一访问次数

时间:2016-01-27 09:11:40

标签: mysql sql

我有这张桌子(访问):

id  |       fb_id    |   flipbook    | 
----     ----------      ---------     
1         1123           november2014        
2         1123           november2014      
3         1127           november2014       
4         1124           november2014    
5         1126           november2014            
6         1123           december2014
7         1124           december2014
8         1125           december2014
9         1123           january2015  
10         1124           january2015
11        1125           january2015
12         1123           february2015
13         1125           february2015
14        1124           february2015
15        1127           february2015
16        1129           march2015
17        1123           march2015
18        1123           march2015
19        1124           march2015
20        1125           march2015
21        1126           march2015
22        1128           march2015

我们总共有5本翻书,在查询之后我想获得以下结果:

5: 10 (because we have 2 users that visited all the flipbooks = 10 visits)
4: 4 (only 1 user visited 4 flipbooks = 4 visits)
3: 0
2: 4 (2 users visited  2 flipbook = 4 visits )
1: 2 (2 users visited only 1 flipbook = 2 visits)

我没有任何疑问可以在此发布此结果,任何想法?

2 个答案:

答案 0 :(得分:3)

我会创建一个子查询,通过fb_id计算不同的翻书。外部查询将计算内部计数并将它们相乘。如果要将结果作为t.visited获取结果,可以使用concat()函数:no_of_visits格式,而不需要任何其他子查询。

select t.visited, count(t.visited) * t.visited as no_of_visits
from
    (select fb_id, count(distinct flipbook) as visited
     from vistits group by fb_id) t
group by t.visited

答案 1 :(得分:1)

SELECT s.cnt ||' : '|| s.cnt*s.cnt2 from (
SELECT p.cnt,count(*) cnt2 from (
SELECT t.fb_ind,count(distinct t.flipbook) as cnt from yourTable t
group by t.fb_ind) p
group by p.cnt) s

这是未经测试的,因此可能需要进行一些语法调整,但它应该有效。

首先 - 区分您的表格,然后 - 分组获取翻转的Num,然后 - 分组查看相同翻转的数量,然后将其连接并进行计算。