我的目标是找到过去7天内访问过我网站的访问者数量,今天也访问过了。
这意味着如果有人访问了05-02
,今天就会在05-02
上计算。
我的查询存在的问题是,如果有人访问了05-01
和05-02
,而且今天也只会访问05-01
。但我希望查询能够在05-02
上计算他。
如何编辑下面的查询来执行此操作?
SELECT COUNT( DISTINCT v.`hash` ) hashCount, DATE( v.`timestamp` ) AS views
FROM audience v
INNER JOIN behaviour b ON v.`hash` = b.`hash`
WHERE v.timestamp
BETWEEN SUBDATE( CURDATE( ) , 7 )
AND CURDATE( )
AND DATE( b.timestamp ) = CURDATE( )
GROUP BY views
答案 0 :(得分:2)
为了方便起见,请带走所有访问过的人并寻找 在过去7天内访问,如果找到一个返回的最后日期 访问。我认为这种方法更容易理解:
select b.`hash` ,
audience.last_visit
from behaviour b
inner join (select v.`hash`, max(v.timestamp) as last_visit from audience v
where DATE(v.timestamp) between date_sub(current_date, interval 7 day) and
date_sub(current_date, interval 1 day)
group by v.`hash`) as audience
on(b.`hash` = audience.`hash`)
where DATE(b.timestamp) = CURDATE();
- 我们加入了一个已经包含我们需要的信息的选择(过去7天内每个哈希的最新访问次数)。
返回的行数是访问过您的访问者数量 今天和上周的页面。
您也可以从您的选择中计算,以获得您要查找的数字作为查询结果:
select count(*) from
(select b.`hash` ,
audience.last_visit
from behaviour b
inner join (select v.`hash`, max(v.timestamp) as last_visit from audience v
where DATE(v.timestamp) between date_sub(current_date, interval 7 day) and
date_sub(current_date, interval 1 day)
group by v.`hash`) as audience
on(b.`hash` = audience.`hash`)
where DATE(b.timestamp) = CURDATE() ) as my_visitors;
- Testdata
drop table if exists your_schema.behaviour;
create table your_schema.behaviour(`hash` varchar(255), `timestamp` timestamp) ;
insert into your_schema.behaviour
values ('ab','2016-05-23'),('ac','2016-05-23');
drop table if exists your_schema.audience;
create table your_schema.audience (`hash` varchar(255), `timestamp` timestamp) ;
insert into your_schema.audience
values ('ab','2016-05-01'),('ab','2016-05-02'),('ab','2016-05-03'),('ab','2016-05-04'),('ab','2016-05-21'),('ab','2016-05-23'),
('ac','2016-05-01'),('ac','2016-05-02'),('ac','2016-05-03'),('ac','2016-05-04'),('ac','2016-05-21'),('ac','2016-05-23'),
('ad','2016-05-01'), ('ad','2016-05-02'), ('ad','2016-05-03'),('ad','2016-05-04'),('ad','2016-05-21'),('ad','2016-05-23');
答案 1 :(得分:1)
您也可以使用 DATE_SUB ,检查以下查询
SELECT COUNT(DISTINCT v.`hash`) AS hashCount, DATE(v.`timestamp`) AS views
FROM audience v
INNER JOIN behaviour b ON v.`hash` = b.`hash`
WHERE views >= DATE_SUB(Now(),INTERVAL 7 DAY)
GROUP BY views
有关更多信息,请访问以下网址
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
答案 2 :(得分:0)
您只需使用DATE - INTERVAL ? DAY
功能即可。检查下面的示例:
SELECT COUNT(DISTINCT v.`hash`) AS hashCount, DATE(v.`timestamp`) AS views
FROM audience v
INNER JOIN behaviour b ON v.`hash` = b.`hash`
WHERE views >= DATE(NOW()) - INTERVAL 7 DAY
GROUP BY views
转到此处了解更多Date and Time Functions。