使用聚合函数查找百分比 MYSQL

Find Percentage using Aggregation Function MYSQL

所以我有 3 tables propertiesproperty_plotsorders。每个 属性 将有许多地块,每个地块的大小可以为 no_sqyds。 现在用户可以购买数量为 no_sqyds 的地块,我存储在 orders table.

properties

property_plots

orders

所以我的问题是如何找到特定地块的购买百分比?另外,如何使用相同的方法找到整个 属性 的购买百分比?

到目前为止,我尝试的是使用这个粗略查询在地块级别找到百分比

((SELECT sum(o.no_sqyds) FROM orders as o 
WHERE o.plot_id = pp.id)*100)/pp.no_sqyds FROM property_plots as pp

基于 table orders table 我可以得到每个地块的百分比,但我也通过结合以下数据查看 属性 水平。 (我必须得到所有地块百分比的平均值才能在 属性 水平上找到?)

plot_id 1 = 100% purchase

plot_id 2 = 66.67% purchase

plot_id 3 = 50%

示例数据库 - https://pastebin.com/RYJwwRqJ

将它们加入并分组并计算。

SELECT 
  property_id
, prop.name AS property_name
, (SUM(order_no_sqyds)/SUM(plot_no_sqyds))*100 AS percentage
, SUM(plot_no_sqyds) AS plot_no_sqyds
, SUM(order_no_sqyds) AS order_no_sqyds
, COUNT(plot_id) AS total_plots
, SUM(total_orders) AS total_orders
FROM
(
    SELECT 
      plot.property_id
    , plot.id AS plot_id
    , plot.no_sqyds AS plot_no_sqyds
    , SUM(ordr.no_sqyds) AS order_no_sqyds
    , COUNT(DISTINCT ordr.id) AS total_orders
    FROM property_plots AS plot
    LEFT JOIN orders AS ordr
      ON ordr.plot_id = plot.id
     AND ordr.property_id = plot.property_id
    GROUP BY 
      plot.property_id
    , plot.id
    , plot.no_sqyds
) q
INNER JOIN properties AS prop
   ON prop.id = q.property_id
GROUP BY property_id, prop.name
ORDER BY property_id
property_id property_name percentage plot_no_sqyds order_no_sqyds total_plots total_orders
1 Lake View Park 66.6667 225 150 3 4

演示 db<>fiddle here

另一种计算它的方法是加入订单的聚合。

SELECT 
  plot.property_id
, prop.name AS property_name
, (SUM(ordr.no_sqyds)/SUM(plot.no_sqyds))*100 AS percentage
, SUM(plot.no_sqyds) AS plot_no_sqyds
, SUM(ordr.no_sqyds) AS order_no_sqyds
, COUNT(DISTINCT plot.id) AS total_plots
, SUM(total_orders) AS total_orders
FROM property_plots AS plot
INNER JOIN properties AS prop
   ON prop.id = plot.property_id
LEFT JOIN (
   SELECT plot_id, property_id
   , SUM(no_sqyds) AS no_sqyds
   , COUNT(DISTINCT id) AS total_orders
   FROM orders
   GROUP BY plot_id, property_id
) AS ordr
  ON ordr.plot_id = plot.id
 AND ordr.property_id = plot.property_id
GROUP BY 
  plot.property_id
, prop.name

仅限地块

SELECT 
  plot.property_id
, plot.id AS plot_id
, (SUM(ordr.no_sqyds)/plot.no_sqyds)*100 AS percentage
, plot.no_sqyds AS plot_no_sqyds
, SUM(ordr.no_sqyds) AS order_no_sqyds
, COUNT(DISTINCT ordr.id) AS total_orders
FROM property_plots AS plot
LEFT JOIN orders AS ordr
  ON ordr.plot_id = plot.id
 AND ordr.property_id = plot.property_id
GROUP BY 
  plot.property_id
, plot.id
, plot.no_sqyds
SELECT orders.plot_id, 
       ROUND(100*SUM(orders.no_sqyds)/MAX(property_plots.no_sqyds)) purchase_percent
FROM orders
JOIN property_plots ON orders.plot_id = property_plots.id
GROUP BY orders.plot_id

https://dbfiddle.uk/?rdbms=mariadb_10.4&fiddle=4c2bad2ff341ba94b3df2f278d1d7778