我有这些记录的表(user_notes):
我想得到平均减肥,问题是有些用户有重复的值。例如:
User 1: weight 20kg
User 1: weight 10kg --> Lost: 10kg
User 2: weight 100kg
User 2: weight 70kg --> Lost: 30kg
Avg weight loss: 20kg <-- Expected result
用户1丢失了10公斤,用户2输了20公斤,但我需要为每个用户标识执行此操作并获得平均减肥。
我怎样才能做到这一点?
答案 0 :(得分:1)
这里的挑战是获得每个用户的第一个和最后一个权重。这是通过在用户级别聚合以获得第一周和最后一周的一种方式:
select tt.iduser, tmax.weight as last_weight, tmin.weight as first_weight,
(tmax.weight - tmin.weight) as diff
from (select iduser, min(week) as minw, max(week) as maxw
from t
group by iduser
) tt join
t tmin
on tmin.iduser = tt.iduser and tmin.week = tt.minw join
t tmax
on tmax.iduser = tt.iduser and tmax.week = tt.maxw;
然后,如果你想要平均减肥:
select avg(tmax.weight - tmin.weight)
from (select iduser, min(week) as minw, max(week) as maxw
from t
group by iduser
) tt join
t tmin
on tmin.iduser = tt.iduser and tmin.week = tt.minw join
t tmax
on tmax.iduser = tt.iduser and tmax.week = tt.maxw
where maxw <> minw;