[英]Sql, compare row values against average of rows in that column
所以我很驚訝我在谷歌搜索后找不到答案所以這里是。 給定以下查詢,該查詢連接來自 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 | ... |
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
;
您應該能夠通過使用執行總利潤總和的嵌套查詢來做到這一點:
... SUM(ql.profit) / (SELECT SUM(profit) FROM q1) ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.