我想更新一个名为ratio的字段。对于比率,我想从我从此查询中获得的两个值计算它。
/*Returns the sum of the latest two entries in two different rows*/
select sum(value) as sum from db.s s
where s.r_id = 76703
group by timeIn
order by timeIn DESC
LIMIT 2;
/*calculate ratio??*/
UPDATE db.r SET ratio = RESULT??
上面的查询给出了两行有两个值 比率应为row1 / row2 然后更新另一个表上的比率字段。
答案 0 :(得分:1)
我几乎可以肯定这个问题有一种更高效,更清洁的解决方案。但是,这也可能有效。
UPDATE db.r SET ratio =
(
select sum(value) as sum from db.s s
where s.r_id = 76703
group by timeIn
order by timeIn DESC
LIMIT 1;
)
/
(
select sum(value) as sum from db.s s
where s.r_id = 76703
group by timeIn
order by timeIn DESC
LIMIT 1,1;
)
答案 1 :(得分:0)
您可以排名,并使用CASE
获取这两个值;
UPDATE r SET ratio = (
SELECT SUM(CASE WHEN c=2 THEN sum ELSE 0 END) /
SUM(CASE WHEN c=1 THEN sum ELSE 0 END)
FROM (
SELECT SUM(value) sum, @c:=@c+1 c
FROM s, (SELECT @c:=0)a
WHERE s.r_id = 76703
GROUP BY timeIn
ORDER BY timeIn
LIMIT 2
)z
);