【问题标题】:Posgre partition by and group where range is true?Postgres 按范围划分和分组,范围为真?
【发布时间】:2020-04-29 16:10:26
【问题描述】:

我有一张表,我想按范围分组,并显示有多少安​​装程序的安装属于特定范围。对于此示例,范围为 [1-3] 和 [4-5]

Installer Size
Ben       5
Ben       5
Sam       4
Sam       1
Ben       1
Sam       2
Sam       NULL

这是我希望使用over partition bycount(*) 看到的:

Installer  CounOf[1-3]  CountOf[4-5]
Ben        1              2
Sam        2              1

我将如何编写这个查询?

【问题讨论】:

    标签: sql postgresql group-by partition


    【解决方案1】:

    对于此任务,您不需要窗口函数(使用over() 子句的函数)。您可以改用条件聚合; Postgres 的filter() 子句对此很方便:

    select 
        installer,
        count(*) filter(where size between 1 and 3) count_of_1_3,
        count(*) filter(where size between 4 and 5) count_of_4_5
    from mytable
    group by installer
    order by installer
    

    Demo on DB Fiddle

    安装程序 | count_of_1_3 | count_of_4_5 :-------- | ------------: | ------------: 本 | 1 | 2 山姆 | 2 | 1

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 2020-09-08
      • 2013-11-04
      相关资源
      最近更新 更多