gpt4 book ai didi

sql - 获取数量的平均值

转载 作者:行者123 更新时间:2023-12-04 11:10:15 24 4
gpt4 key购买 nike

我在计算一些简单的平均值时遇到了问题。我的 table :

id / user / action     / data
1 / a / unit_price / 40
2 / a / quantity / 1
3 / b / unit_price / 70
4 / b / quantity / 2

Unit_price 是一个用户的价格,quantity 是数量。所以我应该得到:(40 + 70 + 70)/3 = 60

如果我做一个

(AVG(action) WHERE action = unit_price)

我得到:

(70+40)/2 = 55

如果我做一个

(SUM(action) WHERE action = unit_price)/(SUM(action) WHERE action = quantity)

我得到:

110/3 = 36.6

我发现最简单的方法是不输入 unit_price,而是输入全局价格,然后在 PHP 代码中进行除法以获得 unit_price,但我希望 SQL 可以为我做点什么。

最佳答案

select coalesce(sum(quantity * unit_price) /sum(quantity), 0) from
(select
sum(case when action='unit_price' then data else 0 end) as unit_price,
sum(case when action='quantity' then data else 0 end) as quantity
from test
group by user) as a

SqlFiddle

关于sql - 获取数量的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12828368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com