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