Sql 查询以返回行中值的百分比 订单数量 项目编号 123 111 245 111 367 111 499 111 555 333

Sql 查询以返回行中值的百分比 订单数量 项目编号 123 111 245 111 367 111 499 111 555 333,sql,sql-server,Sql,Sql Server,您可以使用条件聚合: select avg(case when item_num = '111' then 1.0 else 0 end) from t; 如果每个订单可以有多行: select (count(distinct case when item_num = '111' then order_num end) * 1.0 / count(distinct order_num) ) from t; 或者,您可以使用聚合对所有项目进行计算: select

您可以使用条件聚合:

select avg(case when item_num = '111' then 1.0 else 0 end)
from t;
如果每个订单可以有多行:

select (count(distinct case when item_num = '111' then order_num end) * 1.0 /
        count(distinct order_num)
       )
from t;
或者,您可以使用聚合对所有项目进行计算:

select item_number,
       count(*) * 1.0 / sum(count(*)) over () as ratio
from t
group by item_number;

您可以将总数存储在一个变量中,并使用它来计算sql查询中的百分比

下面是MySQL的示例

SET @cnt := (SELECT COUNT(*) FROM Order);

SELECT (c/(@cnt))*100 AS percentage, item FROM (
        SELECT COUNT(*) as c, Item_Num AS item FROM Order GROUP BY Item_Num
)_;

非常感谢。如果我想显示多个项目编号及其订购百分比,该怎么办?示例:我想显示20%订购次数的项目编号“333”。谢谢!这成功了!