如何在 PostgreSQL 中找到按值分组的整体百分比?

How to find percent of whole grouped by a value in PostgreSQL?

我有2张桌子

Table 1

| order_id | remade_or_not |    
| ---      | ---           |  
| 1        | true          |  
| 2        | false         |  
| 3        | true          |  

Table 2

| order_id | maker_id |  
| ---      | ---      |  
| 1        | 101      |   
| 2        | 101      |  
| 3        | 102      |  

如何在 PostgreSQL 中找到每个 maker_idremade_or_not 百分比?可以在 order_id.
上连接两个表 例如,remade_or_not = true 对于 maker_id 101.

的百分比是多少

您按制造商 ID 计算订单数和是否重新制作价值,然后将其除以按制造商 ID 排列的订单总数。如果您希望将其表示为 0 到 100 之间的小数,请将 1.0 更改为 100.0。

SELECT x.maker_id
     , y.remade_or_not
     , COUNT(*) * 1.0 / COUNT(*) OVER (PARTITION BY x.maker_id) AS pct
FROM table2 x
     INNER JOIN table1 y ON x.order_id = y.order_id
GROUP BY x.maker_id
       , y.remade_or_not;

尝试像下面这样使用条件聚合我假设 remade_or_not 是字符串数据类型,如果它是 bool 那么条件将在侧面情况下改变

select maker_id,
(coalesce(sum(case when remade_or_not='true' then 1 else 0),0)*1.00/count(order_id))*100
    from   tab1 t1 jon tab2 t2 on t1.order_id=t2.order_id group by maker_id

如果 remade_or_not 已经是一个布尔列,那么您可以将其转换为 int 并取 avg():

select t2.maker_id, avg(t1.remade_or_not::int) as remade_pct
  from table_1 t1
       join table_2 t2 
         on t2.order_id = t1.order_id
 group by t2.maker_id;

Working fiddle