2013-05-29 44 views
1

窗函數我有我的,我只是想不通SELECT語句。查詢如下:PostgreSQL中

SELECT 
    count(1), 
    interaction_type_id 
FROM 
    tibrptsassure.d_interaction_sub_type 
GROUP BY 
    interaction_type_id 
HAVING 
    count(interaction_type_id) > 1 
ORDER BY 
count(interaction_type_id) DESC 
LIMIT 5; 

由於我的應用程序不支持使用LIMIT關鍵字,我試圖改變使用rank()功能,像這樣我的查詢:

SELECT 
interaction_type_id, 
rank() OVER (PARTITION BY interaction_type_id ORDER BY count(interaction_type_id) 
DESC) 
FROM 
tibrptsassure.d_interaction_sub_type; 

但是,這樣一來我結束了以下錯誤消息:

ERROR: column "d_interaction_sub_type.interaction_type_id" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: SELECT interaction_type_id, rank() OVER (PARTITION BY inter...  
        ^
    ********** Error ********** 

ERROR: column "d_interaction_sub_type.interaction_type_id" must appear in the GROUP BY clause or be used in an aggregate function 
SQL state: 42803 
Character: 9 

是否存在的rownum() PostgreSQL中的相同呢? (除了使用LIMIT關鍵字來達到同樣的效果,那就是。)

是否有人對我有什麼建議嗎?提前致謝。

+0

這是什麼意思:「我的*應用程序*不支持限制」?編程語言,PostgreSQL,ORM?考慮提供一個SQLFiddle演示,並將你的SQL命令格式化爲源代碼。 – Beryllium

+0

Intelliview Nxt ..我們用來創建報告的門戶。這不支持限制功能。 – Nancy

+1

但它*支持*窗口aggegate函數*(通過...分區...)?所以你可以改變查詢使用聚合函數,但不使用限制?換句話說,你可以在你的查詢中使用什麼? – Beryllium

回答

1

測試了以下工作(這是標準的PostgreSQL語法和應該工作)是否:

with 
t as (
    select 1 as id union all 
    select 1 as id union all  
    select 2 union all 
    select 2 union all  
    select 3) 

select 
    id 
from 
    t 
group by 
    id 
having 
    count(id) > 1 
order by 
    id desc 
limit 1 

如果這個工程,那麼你有一些語法問題。如果這不起作用,那麼你還有其他一些問題 - 也許你正在使用的軟件受到一些非常奇怪的限制。

您還可以使用row_number(),但它是不是很有效的方法:

with 
t as (
    select 1 as id union all 
    select 1 as id union all  
    select 2 union all 
    select 2 union all  
    select 3) 

, u as (
    select 
     id, 
     count(*) 
    from 
     t 
    group by 
     id 
    ) 

, v as (
    select 
     *, 
     row_number() over(order by id) c 
    from 
     u 
    ) 

select 
    * 
from 
    v 
where 
    c < 2 
1

的問題是在我的查詢,即有一個語法錯誤。 我需要的是前5 category_idtype_id前5名情況在每個type_idsub_type_id每個category_id和頂部5個實例。要做到這一點,我在下面的方式改變了查詢,並最終得到了預期的輸出:

SELECT * FROM (
SELECT t1.int_subtype_key, t2.interaction_sub_type_desc, interaction_category_id, 
interaction_type_id, interaction_sub_type_id, count(interaction_sub_type_id) AS 
subtype_cnt, 
rank() 
over (PARTITION BY interaction_category_id, interaction_type_id ORDER BY 
count(interaction_sub_type_id) DESC) AS rank 
FROM tibrptsassure.f_cc_call_analysis t1 INNER JOIN 
tibrptsassure.d_interaction_sub_type t2 ON t1.int_cat_key = t2.intr_catg_ref_nbr 
AND t1.int_subtype_key = t2.intr_sub_type_ref_nbr INNER JOIN 
tibrptsassure.d_calendar t3 ON t1.interaction_date = t3.calendar_date GROUP BY 
t2.interaction_sub_type_desc, t1.int_subtype_key, interaction_category_id, 
interaction_type_id, interaction_sub_type_id) AS sub_type 
WHERE rank <= 5; 

感謝大家的關注和幫助我與此有關。

+0

所以基本上你投降使用子查詢,而不是我知道任何其他方式。 –