开发者

Getting the min() of a count(*) column

I have a table called Vehicle_Location containing the columns (and more):

ID               NUMBER(10)
SEQUENCE_NUMBER NUMBER(10) 
TIME            DATE 

and I'm trying to get the min/max/avg number of records per day per id.

So far, I have

select id, to_char(time), count(*) as c
  from vehicle_location
 group by id, to_char(time), min having id = 16

which gives me:

ID                     TO_CHAR(TIME) COUN开发者_如何转开发T(*)               
---------------------- ------------- ---------------------- 
16                     11-05-31      159                    
16                     11-05-23      127                             
16                     11-06-03      56                  

So I'd like to get the min/max/avg of the count(*) column. I am using Oracle as my RDBMS.


I don't have an oracle station to test on but you should be able to just wrap the aggregator around your SELECT as a subquery/derived table/inline view

So it would be (UNTESTED!!)

SELECT 
    AVG(s.c)
    , MIN(s.c)
    , MAX(s.c)
    , s.ID
FROM
    --Note this is just your query
    (select id, to_char(time), count(*) as c from vehicle_location group by id, to_char(time), min having id = 16) as s
GROUP BY s.ID

Here's some reading on it:
http://www.devshed.com/c/a/Oracle/Inserting-SubQueries-in-SELECT-Statements-in-Oracle/3/

EDIT: Though normally it is a bad idea to select both the MIN and MAX in a single query.

EDIT2: The min/max issue is related to how some RDBMS (including oracle) handle aggregations on indexed columns. It may not affect this particular query but the premise is that it's easy to use the index to find either the MIN or the MAX but not both at the same time because any index may not be used effectively.
Here's some reading on it:
http://momendba.blogspot.com/2008/07/min-and-max-functions-in-single-query.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜