date value
2012-01-01 124
2012-01-02 250
2012-04-21 56
2012-07-06 198
2012-09-24 650
2013-07-07 1000
我想“汇总”2012-01-01至2012-07-06的价值,并在同一张表中除以2012-01-01至2013-07-07的“总和”。< / p>
答案 0 :(得分:1)
SELECT (SELECT SUM(value) FROM yourTable WHERE date BETWEEN '2012-01-01' AND '2012-07-06') /
(SELECT SUM(value) FROM yourTable WHERE date BETWEEN '2012-01-01' AND '2013-07-07')
或:
SELECT SUM(IF(date BETWEEN '2012-01-01' AND '2012-07-06'), value, 0)) /
SUM(IF(date BETWEEN '2012-01-01' AND '2013-07-07'), value, 0))
FROM yourTable
答案 1 :(得分:0)
Select sum(if(date between ... and ..., value, 0)/sum(value)
from table where date beteen ... and ...
在if()中使用较小的日期范围,在where条件中使用较宽的日期范围。