返回组内的总百分比

时间:2018-08-31 05:03:00

标签: sql

使用以下示例数据库:https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_avg

我正在尝试创建一个表格,该表格返回每个国家/地区每个类别的订单百分比。因此理想情况下看起来像这样:

Country   CategoryName  Num_of_orders  % of orders
Argentina  Confections       1            0.50
Argentina   Produce          1            0.50
Austria    Beverages         5            0.17
Austria    Condiments        6            0.21

因此,由于阿根廷只有两个订单,所以糖果将占50%,因此也会生产。

到目前为止,我得到的最接近的结果是返回订单总数的一定百分比,但忽略了国家/地区。

SELECT c.country, ca.categoryname, count(o.orderid) as Num_of_orders, 
    count(*)/(select 1.0*count(*) from orders) as percentage
from orders as o
join customers as c on c.customerid = o.customerid
join orderdetails as od on od.orderid = o.orderid
join products as p on p.productid = od.productid
join categories as ca on ca.categoryid = p.categoryid
group by 1, 2

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为您需要类似以下内容的内容,即按子查询中的国家/地区选择计数,而不是所有订单的计数。

SELECT c.country, ca.categoryname, count(o.orderid) as Num_of_orders, 
    count(*)/(select 1.0*count(*) from orders o2 join customers c2 on c2.customerid = o2.customerid join orderdetails od2 on od2.orderid = o2.orderid WHERE c2.country=c.country) as percentage
from orders as o
join customers as c on c.customerid = o.customerid
join orderdetails as od on od.orderid = o.orderid
join products as p on p.productid = od.productid
join categories as ca on ca.categoryid = p.categoryid
group by 1, 2

此版本适用于示例数据库,但根据实际查询所针对的数据库,您可能会考虑对分区而不是子查询进行计数,或者至少使用通用表表达式来避免编写某些联接就像我在这里所做的一样。