MySQL - 检索某个计数

时间:2013-07-04 10:09:57

标签: mysql sql join subquery

所以,基本上我必须生成一个关于页面访问次数的报告..好吧,假设这是我的表格数据。 (注意:请假设所有记录的日期时间值)
    访客dtime
      a       ç
      b
      一个
      d
      b
      e 2013-04-31 03:14:29
      s 2013-04-01 03:14:29
      a 2013-04-01 03:14:29
      b 2013-04-01 03:14:29
      b 2013-04-01 03:14:29
      c 2013-04-31 03:14:29
      c第2       b第2个       d 3       d 3       第3个       b 4       b

因此,如果用户从1st to 3rd选择,我必须打印 日期PageLoads唯一访问次数首次访问返回访问次数

1st   4   3   1  2

2nd   3   2   0  2

3rd   3   2   0  2

pageloads for 1st are - s a b bunique visits - s a b 问题是在与之前的每位访问者进行比较时,首次访问时间仅为s。 第二次访问次数为0,因为没有人第一次访问

我查找网页加载和唯一访问的查询是 -

select distinct DATE(dtime) as ddate,count(visitors) as ploads, 
count(distinct visitors) as uvisits,
from table1 where  dtime >= '2013-04-1 00:00:01' and dtime <= '2013-04-3 23:59:59'
group by DATE(dtime) order by ddate desc;

如何查找每个日期的首次访问?

2 个答案:

答案 0 :(得分:0)

如果's'是第一次访问那么

使用和函数

sum(ifnull((select visitors from yourtable where dtime<'2013-04-1 00:00:01' ),1,0)) as FirstTime


select DATE(dtime) as ddate,
    count(visitors) as ploads, 
    count(distinct visitors) as uvisits,
    sum(ifnull((select visitors from yourtable where dtime<'2013-04-1 00:00:01' ),1,0)) as FirstTime,
    count(distinct visitors)-
    sum(ifnull((select visitors from yourtable where dtime<'2013-04-1 00:00:01' ),1,0)) as ReturningVisits
from yourtable where dtime >= '2013-04-1 00:00:01' 
and dtime <= '2013-04-3 23:59:59' 
group by DATE(dtime) 
order by ddate desc;

答案 1 :(得分:0)

首先,您需要创建一个返回第一次访问者的子查询。

select visitor,min(dtime) as firstDate from table
group by visitor

现在你知道访客和他的第一次访问日期..

select distinct DATE(dtime) as ddate,
       count(A.visitors) as ploads, 
       count(distinct visitors) as uvisits,
       count(b.visitors) as FirstTime,
       count(a.visitors)-count(b.visitors) as ReturnVisits
from table A
left join (select visitors,min(dtime) as firstDate from table group by visitors) B 
     on b.visitors=a.visitors and b.firstDate = a.dtime
where  dtime >= '2013-04-1 00:00:01' and dtime <= '2013-04-3 23:59:59'
group by DATE(dtime) 
order by ddate desc;

我没有在这台机器上安装mySQL,所以原谅任何语法错误,但我希望这能指出你正确的方向。