1

I need to query the top 5 value from tableA. Such as below

    select id, count(occurrence), date 
    from 
    (select id, unnest(value) as occurrence, date from tableA) as a
    group by id, occurrence, date 
    order by occurrence desc 
    limit 5

 id  | occurrence |   date   
-----+-------+----------
 330 |    11 | 20141015
 400 |    11 | 20141015
 390 |    10 | 20141015
 240 |    10 | 20141015
 501 |    10 | 20141015

and after received the ids, query the same tableA to get all the values of the id for other dates ranges from 20140101 until 20141015.

expected result:

 id  | occurrence |   date   
-----+-------+----------
 330 |    11 | 20141015
 400 |    11 | 20141015
 390 |    10 | 20141015
 240 |    10 | 20141015
 501 |    10 | 20141015
 330 |    0  | 20141014
 400 |    1  | 20141014
 390 |    10 | 20141014
 240 |    15 | 20141014
 501 |    10 | 20141014
 330 |    11 | 20141013
 400 |    11 | 20141013
 390 |    11 | 20141013
 240 |    19 | 20141013
 501 |    10 | 20141013

But how exactly can I do that?

My postgresql version is 8.1 and I can't use partition(if any of u want to suggest that)


edit

select  id, count(value) as occurrence, date
from tableA
where id = ANY(
    select array(
        select id
        from (
            select date, unnest(id) as id
            from tableA where date>='20140101' and date<='20141015'
            )as a
        )
)
group by id, date

doesn't return anything. is my array correct?

2 Answers 2

0

You may try select sth from table where dt > 20140101 and dt < 20141015 and row_num <= 5 this will give you the right answer.

2
  • can you give us more detail? what do you exactly want? Oct 13, 2015 at 15:14
  • id is an array if u notice Oct 13, 2015 at 15:16
0
select id, count(value) as occurrence, date
from t
where id in (
    select id
    from (
        select id, count(value) as occurrence, date 
        from t 
        group by id, date 
        order by occurrence desc 
        limit 5
    ) s
) q
group by id, date
2
  • I don't think we need to name everything IN () as q?? Oct 13, 2015 at 15:03
  • value is actually an array. Sorry, I have edited my question. Thanks in advance Oct 13, 2015 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.