1

我有一个我无法弄清楚的 SELECT 语句。查询如下:

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 关键字来达到相同的结果,也就是说。)

有人对我有什么建议吗?提前致谢。

4

2 回答 2

1

问题出在我的查询中,即存在语法错误。我需要的是 in each 的前 5 个category_id和前 5 个实例以及in type_ideachcategory_id的前 5 个实例。为此,我通过以下方式更改了查询,最终得到了预期的输出:sub_type_idtype_id

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;

感谢大家的关注和帮助我。

于 2013-05-30T06:29:47.940 回答
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
于 2013-05-29T12:21:31.317 回答