开发者

sql to look at maximum, calculated hourly

Need some help in some SQL.

I have the following report that I need to build, but I ideally want to try and build it using an SQL Script, rather than having to have a procedure that runs every hour etc.

The business problem we are solving is basically calculating the maximum amount of locations that are occupied in a given week by products, calculated hourly.

I know I can do this by running a procedure every hour that counts the amount and inserts it into a table. I would then query this table at the end of the week and see which hour of which day had the greatest number.

Ideally I want to do this without using procedures. I have SQL written that can tell me the number at any point in time (between say the hours of 10-11AM on Monday).

Rather than copying and pasting this SQL script 24 x 7 times (1 for each hour of开发者_如何学C the day), is there something else I can do through SQL script here? Could I create a maintenance table that has every day, and time period listed (e.g. columns would be: day, hour_start, hour_end), join that onto my query and use a max function?

I'm pretty sure that it can't be done through strait SQL but I'm not a fan of time dependant procedures running (e.g. what if the server was to go offline).

Any advice appreciated!


Assuming a data structure like that:

create table room_usage ( 
   roomnumber number(6),
   occupied_by varchar2(20),
   startdate date,
   enddate date
);

You could query the number of occupied rooms per hour like that:

with datgen as 
  (select to_date('2008-09-19','yyyy-mm-dd')+(rownum-1)/24 d 
     from dual
     connect by rownum<=168)
select d, (select count(*) from room_usage
             where startdate<=datgen.d
               and enddate>=datgen.d) occupied
  from datgen;

to_date('2008-09-19','yyyy-mm-dd') is the start date for your query, 168 the number of hours you want reported.

EDIT: To get the maximum number and the lastest date with that number, use

with datgen as 
  (select to_date('2008-09-19','yyyy-mm-dd')+(rownum-1)/24 d 
     from dual
     connect by rownum<=168),
occ_count as (     
  select d, (select count(*) from room_usage
               where startdate<=datgen.d
                 and enddate>=datgen.d) occupied
    from datgen)
select d, occupied from (select * from occ_count order by occupied desc, d desc)
 where rownum=1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜