Sql,将行值与该列中的行的平均值进行比较

时间:2021-07-21 20:05:09

标签: mysql sql

所以我很惊讶我在谷歌搜索后找不到答案所以就这样了。给定以下查询,该查询连接来自 3 个表的数据并聚合关于 store_id 的数据。我想要一个额外的列来比较该行的利润与利润列的平均值。我添加了索引列来说明它的外观。第 1 行将是 500 / 500(利润列的平均值)等。

SELECT 
    region, store_id, SUM(q1.revenue), SUM(q1.profit) as 'profit', 
    SUM(q1.profit) / SUM(revenue) * 100 as 'percentage'
FROM ( SELECT
    regions.region_name as 'region', s.store_id,
    s.revenue as 'revenue', (s.revenue - s.costs) as 'profit'
FROM
    store_sales s
    JOIN stores ON s.store_id = stores.store_id
    JOIN regions ON stores.store_id = regions.store_id
    JOIN weeks ON s.week_id = weeks.week_id
WHERE
    weeks.end_date BETWEEN '2020-01-01' AND '2020-03-31') as q1
GROUP BY
    store_id
ORDER BY
    store_id```

| region | store_id | revenue | profit | %age | index |
-------------------------------------------------------
| north  | 01       | 2000    | 500    | 25   | 1.00  |
| north  | 02       | 1000    | 500    | 50   | 1.00  |
| north  | 03       | 3000    | 50     | 1.6  | 0.10  |
| south  | 04       | 4000    | 800    | 20   | 1.60  |
| south  | 05       | 1200    | 400    | 33   | 0.80  |
| south  | 06       | 800     | 200    | 25   | ...   |
| east   | 07       | 1800    | 450    | 25   | ...   |
| east   | 08       | 2200    | 1100   | 50   | ...   |

2 个答案:

答案 0 :(得分:1)

select t1.*,
       t1.profit / sum(t1.profit) over() idx
  from (
SELECT 
    region, store_id, SUM(q1.revenue), SUM(q1.profit) as 'profit', 
    SUM(q1.profit) / SUM(revenue) * 100 as 'percentage'
FROM ( SELECT
    regions.region_name as 'region', s.store_id,
    s.revenue as 'revenue', (s.revenue - s.costs) as 'profit'
FROM
    store_sales s
    JOIN stores ON s.store_id = stores.store_id
    JOIN regions ON stores.store_id = regions.store_id
    JOIN weeks ON s.week_id = weeks.week_id
WHERE
    weeks.end_date BETWEEN '2020-01-01' AND '2020-03-31') as q1
GROUP BY
    store_id
ORDER BY
    store_id
) t1
;

答案 1 :(得分:0)

您应该能够通过使用计算总利润总和的嵌套查询来做到这一点:

... SUM(ql.profit) / (SELECT SUM(profit) FROM q1) ...