MySQL 使用 where 子句按百分比分组

MySQL group by percent with where clause

我有 table 个产品 具有以下字段和值:

  ID | Productname | Productprice | Supplier | Available |
+----+-------------+--------------+----------+-----------+
|  1 | Tshirt      | 20           | CompanyA |    Yes    |
|  2 | Pants       | 45           | CompanyA |    Yes    |
|  3 | Shoes       | 95           | CompanyB |    Yes    |
|  4 | Socks       | 12           | CompanyA |     No    |
|  5 | Trainer     | 50           | CompanyA |    Yes    |

如何查询A公司状态为Available=Yes的产品有多少百分比?

考虑到“百分比”是指该公司所有行中可用的行数:

select Supplier, TotalAvailable / Total from(
   select 
      Supplier, 
      sum( if(Available = 'Yes',1,0) ) as TotalAvailable, 
      count(*) as Total
   from
      Products
   where
      Supplier = 'CompanyA'
   group by
      Supplier
) a

或者您可以使用

select 
   Supplier, 
   sum( if(Available = 'Yes',1,0) ) / count(*) as Percent 
from
   Products
where
   Supplier = 'CompanyA'
group by
   Supplier

请注意,您必须按照您的意图处理“百分比”:乘以 100、舍去小数以表示等。

要获得出现在 CompanyA 中的可用产品占所有产品的百分比,您可以使用子查询来计算。

SELECT COUNT(*) * 100 / (SELECT COUNT(*) FROM `products`) as `percentage`
FROM `products` WHERE `supplier` = 'CompanyA' and `available` = 'Yes'

根据您的数据样本,上述查询应该return

   percentage
+-----+-------+
|   60.0000   |