我有一个问题,很容易计算一些简单的平均值。我的表:
id / user / action / data
1 / a / unit_price / 40
2 / a / quantity / 1
3 / b / unit_price / 70
4 / b / quantity / 2
Unit_price是用户的价格,数量是数量。所以我应该得到: (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可以为我做点什么。
答案 0 :(得分:6)
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
答案 1 :(得分:3)
你可以使用这样的东西,它基本上将数据转换为更有用的格式,然后获得你需要的值:
select avg(unit_price) AvgUnitPrice,
sum(unit_price*quantity)/sum(quantity) AvgPrice
from
(
select user,
max(case when action = 'unit_price' then data end) unit_price,
max(case when action = 'quantity' then data end) quantity
from table1
group by user
) x;
答案 2 :(得分:2)
好的,显然您的表格设计不是最佳的,您应该将unit_price
和quantity
作为单独的列。但是,使用你拥有的东西,试试这个:
SELECT SUM(A.data*B.data)/SUM(B.data) Calculation
FROM ( SELECT user, data
FROM YourTable
WHERE action = 'unit_price') AS A
INNER JOIN (SELECT user, data
FROM YourTable
WHERE action = 'quantity') AS B
ON A.user = B.user
答案 3 :(得分:2)
我会加入表格,以便将两条记录列在一行
SELECT
SUM(unit_price * quantity) / SUM(quantity) AS average_unit_price
FROM
(SELECT
U.data AS unit_price, Q.data AS quantity
FROM
theTable U
INNER JOIN theTable Q
ON U.user = Q.user
WHERE
U.action = 'unit_price' AND
Q.action = 'quantity')
如果每个用户有两个以上的记录,并且两个记录的ID都是连续的,那么你必须将WHERE子句改为
WHERE
U.action = 'unit_price' AND
Q.action = 'quantity' AND
U.id + 1 = Q.id
注意:
如果您计算AVG(unit_price * quantity)
,您将获得每位用户的平均金额。
(1 * 40 + 2 * 70)/ 2 = 90
如果您计算SUM(unit_price * quantity) / SUM(quantity)
,则会获得平均单价。
(1 * 40 + 2 * 70)/ 3 = 60
答案 4 :(得分:0)
你的桌子设计看起来不太好。
改为制作2张桌子:
ITEM
ItemId int not null PK,
Name varchar(200) not null,
UnitPrice decimal (10,2) not null
SALES
SalesId int not null PK,
ItemId int not null FK,
Quantity decimal(10,2)
PK - 主键,FK - 外键
平均值:
select
I.Name, avg(I.UnitPrice * S.Quantity) as avgSales
from
Sales S
join Items I on I.ItemId = S.ItemId
group by
I.Name
答案 5 :(得分:0)
这样的事情应该有效;语法可能不完美,因为我没有尝试过,但你至少得到了主要的想法。
SELECT sumUnitPrice.sum / sumQuantity.sum
FROM
(
(SELECT SUM(data) as sum
FROM WhateverTheHellYourTableIsNamed
WHERE action = 'unit_price') sumUnitPrice
(SELECT SUM(data) as sum
FROM WhateverTheHellYourTableIsNamed
WHERE action = 'quantity') sumQuantity
)