如何在 PostgreSQL 中使用多个分区

蚂蚁

我们如何根据业务的计数输出列。如果显示的业务频率相同,我们将订购库存商品最多的业务 SUM(Inventory) - SUM(Total Sold)
给定下表

Business      | Product   | Total_Sold |  Inventory
---------------------------------------------------
Jane's        | Shoes     |  10        |    30 
Jane's        | Top       |  20        |    14 
Jane's        | Top       |  20        |    21 
Smith's       | Bottom    |  50        |    30 
Kamp's        | Shoes     |  20        |    40 
Kamp's        | Top       |  40        |    50 
Kamp's        | Bottom    |  50        |    70 

输出

Business      | Product
------------------------
Kamp's        | Shoes  
Kamp's        | Top     
Kamp's        | Bottom   
Jane's        | Shoes     
Jane's        | Top       
Jane's        | Top      
Smith's       | Bottom   

Kamp's 将首先显示,因为它出现最多且库存最多 (70)。Jane's 排在第二位,因为它也出现了 3 次,但它只有 15 件商品。

下面的查询返回 Jane's 在 Kamp's 之前,因为 Jane's 在表中出现不同。

SELECT business, product
FROM  (
   SELECT business, product
        , count(*) OVER (PARTITION BY business) AS ct
   FROM TABLE
   ) sub
ORDER  BY ct DESC, business, product;

下面的查询计算到库存总量

SELECT business, SUM(total_sold)-SUM(inventory) as diff
FROM TABLE
GROUP by business
ORDER by COUNT(distinct product) DESC, diff ASC

是否可以添加一个新分区来处理 group by 并将这些查询组合在一起?

约格什·夏尔马

您可以使用窗口函数:

select *
from(select *, count(*) over (partition by business) as businesscnt,
               sum(inventory-total_sold) over(partition by business) as closingqty
     from t
     ) t
order by businesscnt desc, closingqty desc;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

春季:如何在PostgreSQL中使用KeyHolder

如何在JdbcTemplate中使用PostgreSQL hstore / json

如何在r2dbc-postgresql中使用EnumCodec

如何在Spring,JPA和PostgreSQL中使用DayOfWeek?

如何在Kubernete中使用AWS EBS挂载PostgreSQL卷

如何在一个PostgreSQL查询中使用多个WITH语句?

如何在PostgreSQL中使用ON CONFLICT和RETURNING?

如何缓存分区数据集并在多个查询中使用?

如何在PostgreSQL的tryCatch中使用dbGetQuery?

如何在Firebird中使用(PostgreSQL的DISTINCT ON)?

如何在Postgresql查询中使用多个“唯一索引推断”

如何在PostgreSQL中使用父项更新JSONB对象

如何在PostgreSQL中使用LAST_VALUE?

如何在IN查询中使用PostgreSQL varchar列值

如何在PostgreSQL中使用子查询进行更新

何时以及如何在PostgreSQL中使用窗口函数?

如何在PostgreSQL和Hibernate / Spring中使用LIMIT子句

如何在Django中使用PostgreSQL的“文本”列类型?

如何在squeryl(PostgreSQL)中使用一个序列自动递增多个表?

我如何在Postgresql命令行中使用mwdumper

如何在PostgreSQL中使用日期格式?

如何在javascript中使用postgresql?

如何在PostgreSQL中使用参数

如何在PostgreSQL中使用Gin索引

如何在PostgreSQL中使用循环序列执行排序

如何在蒸气中使用 PostgreSQL 事务

如何在 postgresql 中使用 age() 函数

如何在 sequalize PostgreSQL 中使用 $and

如何在 WHERE IN 子句中使用 PostgreSQL 数组?