我正在尝试执行查询,以便在过去一小时和最后两小时内获取数据。它只是一个点击反击。
所以我想得到如下结果集:
id, page_url, last_hour_hits, two_last_hours_hits
表格非常简单:
id (autonumber)
page_url
time_stamp
我尝试了以下查询:
SELECT
page_url,
COUNT(page_url) AS last_hour_hits
FROM stats
WHERE time_stamp > '2015-08-01 00:00:00'
GROUP BY page_url
(' 2015-08-01 00:00:00'计算最后一小时)
它工作正常,但我现在知道如何添加' two_last_hours'计数器。
提前谢谢。
答案 0 :(得分:1)
使用MySQL,您可以使用布尔表达式返回1表示true的事实,并将查询简化为:
SELECT
page_url
,sum(time_stamp > (now() - interval 1 hour)) as last_hour_hits
,sum(time_stamp > (now() - interval 2 hour)) as two_last_hours_hits
FROM stats
GROUP BY page_url;
这使用now()
来获取当前时间并根据需要减去间隔。
答案 1 :(得分:0)
您可以在两个结果集之间使用连接 - 一个用于一个小时,另一个用于两个小时:
SELECT stats.page_url, last_hour_hits, last_two_hours_hits from
stats inner join (
SELECT page_url, COUNT(page_url) AS last_hour_hits
FROM stats WHERE time_stamp > '2015-08-01 00:00:00'
GROUP BY page_url ) as last_hour
on stats.page_url = last_hour.page_url
inner join (
SELECT page_url, COUNT(page_url) AS last_two_hours_hits
FROM stats WHERE time_stamp > '2015-07-31 23:00:00'
GROUP BY page_url ) as last_two_hours
on stats.page_url = last_two_hours.page_url
答案 2 :(得分:0)
只需在两个小时之前(' 2015-07-31 23:00:00')放置您的WHERE条款,并在最后一小时计算一个案例(' 2015-08- 01 00:00:00'):
SELECT
page_url,
COUNT(DISTINCT CASE WHEN time_stamp > '2015-08-01 00:00:00' THEN id ELSE NULL END) as last_hour_hits
COUNT(*) AS two_last_hours_hits
FROM stats
WHERE time_stamp > '2015-07-31 23:00:00'
GROUP BY page_url;