我需要回答的问题是“我们在60分钟内收到的最大页面请求数是多少?”
我有一张类似于此的表格:
date_page_requested date;
page varchar(80);
我正在寻找任何60分钟时间段内的最大行数。
我认为分析函数可能会让我在那里,但到目前为止,我正在画一个空白。
我希望指向正确的方向。
答案 0 :(得分:2)
您可以在答案中找到一些可行的选项,这里有一个使用Oracle的“Windowing Functions with Logical Offset”功能而不是连接或相关子查询的选项。
首先是测试表:
Wrote file afiedt.buf
1 create table t pctfree 0 nologging as
2 select date '2011-09-15' + level / (24 * 4) as date_page_requested
3 from dual
4* connect by level <= (24 * 4)
SQL> /
Table created.
SQL> insert into t values (to_date('2011-09-15 11:11:11', 'YYYY-MM-DD HH24:Mi:SS'));
1 row created.
SQL> commit;
Commit complete.
现在T每小时每小时包含一行,在上午11:11:11有一行。查询分为三个步骤。步骤1是,对于每一行,获取行后一小时内的行数:
1 with x as (select date_page_requested
2 , count(*) over (order by date_page_requested
3 range between current row
4 and interval '1' hour following) as hour_count
5 from t)
然后按hour_count分配排序:
6 , y as (select date_page_requested
7 , hour_count
8 , row_number() over (order by hour_count desc, date_page_requested asc) as rn
9 from x)
最后选择具有最多行数的最早行。
10 select to_char(date_page_requested, 'YYYY-MM-DD HH24:Mi:SS')
11 , hour_count
12 from y
13* where rn = 1
如果多个60分钟的窗口以小时数计算,上面只会给你第一个窗口。
答案 1 :(得分:0)
这应该给你所需要的,返回的第一行应该有 页数最多的小时。
select number_of_pages
,hour_requested
from (select to_char(date_page_requested,'dd/mm/yyyy hh') hour_requested
,count(*) number_of_pages
from pages
group by to_char(date_page_requested,'dd/mm/yyyy hh')) p
order by number_of_pages
答案 2 :(得分:0)
这样的事情怎么样?
SELECT TOP 1
ranges.date_start,
COUNT(data.page) AS Tally
FROM (SELECT DISTINCT
date_page_requested AS date_start,
DATEADD(HOUR,1,date_page_requested) AS date_end
FROM @Table) ranges
JOIN @Table data
ON data.date_page_requested >= ranges.date_start
AND data.date_page_requested < ranges.date_end
GROUP BY ranges.date_start
ORDER BY Tally DESC
答案 3 :(得分:0)
对于PostgreSQL,我首先可能会为这个分钟对齐的“窗口”写这样的东西。您不需要OLAP窗口函数。
select w.ts,
date_trunc('minute', w.ts) as hour_start,
date_trunc('minute', w.ts) + interval '1' hour as hour_end,
(select count(*)
from weblog
where ts between date_trunc('minute', w.ts) and
(date_trunc('minute', w.ts) + interval '1' hour) ) as num_pages
from weblog w
group by ts, hour_start, hour_end
order by num_pages desc
Oracle也有一个trunc()函数,但我不确定格式。我要么在一分钟内查看,要么离开去看朋友的滑稽表演。
答案 4 :(得分:0)
WITH ranges AS
( SELECT
date_page_requested AS StartDate,
date_page_requested + (1/24) AS EndDate,
ROWNUMBER() OVER(ORDER BY date_page_requested) AS RowNo
FROM
@Table
)
SELECT
a.StartDate AS StartDate,
MAX(b.RowNo) - a.RowNo + 1 AS Tally
FROM
ranges a
JOIN
ranges b
ON a.StartDate <= b.StartDate
AND b.StartDate < a.EndDate
GROUP BY a.StartDate
, a.RowNo
ORDER BY Tally DESC
或:
WITH ranges AS
( SELECT
date_page_requested AS StartDate,
date_page_requested + (1/24) AS EndDate,
ROWNUMBER() OVER(ORDER BY date_page_requested) AS RowNo
FROM
@Table
)
SELECT
a.StartDate AS StartDate,
( SELECT MIN(b.RowNo) - a.RowNo
FROM ranges b
WHERE b.StartDate > a.EndDate
) AS Tally
FROM
ranges a
ORDER BY Tally DESC