【问题标题】:Postgres/Redshift Count last 5 rows by statusPostgres/Redshift 按状态统计最后 5 行
【发布时间】:2018-10-17 12:10:07
【问题描述】:

我有一张桌子 A:

id, pid, status
---------------
1 | x |   3
2 | x |   2
3 | y |   0
4 | y |   1
5 | z |   3
6 | y |   1
7 | x |   2
8 | z |   3

我需要按pid 分组,计算最后 5 行(按 id 排序)中有多少具有状态 3。

所以我想要得到的是:

pid, is_3
---------
x  | 1
y  | 0
z  | 2

我正在尝试通过如下查询来实现这一点:

SELECT pid, 
COUNT(CASE WHEN status=3 THEN 1 END) AS is_3 
FROM A 
GROUP BY pid 
ORDER BY id desc
LIMIT 5;

请注意,我尝试通过按 id 排序来获取给定 pid 的最后 5 行,因为这里 id 是一个序列。

但我收到错误 ERROR: column "A.id" must appear in the GROUP BY clause or be used in an aggregate function。显然我在 SQL 方面很糟糕。如果可能的话,关于如何最好地实现这种以性能为导向的想法有什么想法吗?

谢谢

【问题讨论】:

    标签: sql postgresql amazon-redshift


    【解决方案1】:

    您可以使用窗口函数来获取行号(类似于聚合但实际上不是),然后过滤

    select pid, sum(case when status=3 then 1 else 0 end) as status_3_cnt
    from (
        select *, row_number() over (partition by pid order by id desc)  
        from your_table
    )
    where row_number<=5
    group by 1
    

    article 中有关窗口函数的更多信息

    【讨论】:

      猜你喜欢
      • 2020-08-21
      • 2018-02-06
      • 1970-01-01
      • 2018-02-09
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      相关资源
      最近更新 更多