sql - PostgreSQL 中的窗口函数

标签 sql postgresql window-functions

我无法理解我的 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

在 PostgreSQL 中是否有等同于 rownum() 的东西? (除了使用 LIMIT 关键字来实现相同的结果之外。)

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

最佳答案

测试以下是否有效(它是标准的 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

关于sql - PostgreSQL 中的窗口函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16807901/

相关文章:

sql - 创建所有可能的组合

sql - 通过均匀跳过行来选择固定行数

sql-server - 在开窗函数中使用 Case ( OVER (Partition))

apache-spark - 与滞后函数和窗口函数一起使用时动态更新 Spark 数据帧列

mysql - 在单个查询中我想从两个不同的表获取数据?

sql - MySQL 外键数据库查询问题

mysql - 如何在 zend db 上构建嵌套选择

PostgreSQL/PGAdmin4 错误 : there is no unique constraint matching given keys for referenced table

sql - 如何根据列选择行数

SQL : transform union query to a single query