2015-10-13 27 views
1

我需要查詢tableA中排名前5的值。如下面從一系列日期中獲取所有排名前5的id(數組)

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 

並收到的ID後,查詢同一個表A來獲取ID的所有值用於其它日期的範圍是從20140101到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 

但我究竟該怎麼辦那?

我的PostgreSQL的版本是8.1,我不能使用分區(如果任何U想暗示)


編輯

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 

不返回任何東西。我的陣列是否正確?

回答

0

您可以嘗試從dt> 20140101和dt < 20141015以及row_num < = 5的表中選擇某項,這會給您正確的答案。

+0

我懷疑這個答案是否正確... – momokjaaaaa

+0

你能給我們更多的細節嗎?你到底想要什麼? –

+0

id是一個數組,如果你注意到 – momokjaaaaa

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 
+0

我不認爲我們需要將所有IN()命名爲q? – momokjaaaaa

+0

值實際上是一個數組。對不起,我編輯了我的問題。在此先感謝 – momokjaaaaa

+0

試圖使用其中id = ANY()但無法工作 – momokjaaaaa

相關問題