如何在 PostgreSQL 中使用多个分区

How to use multiple partitions in PostgreSQL

我们如何根据业务的数量输出列。如果商家显示的频率相同,我们会订购库存商品最多的商家 SUM(库存)- SUM(总售出)
鉴于以下 table

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 件库存。

下面的查询 returns Kamp's 之前的 Jane's 与 Jane's 在 table 中出现的不同。

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

能否添加一个新分区来处理分组依据并将这些查询组合在一起?

您可以使用window函数:

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;