我有一个像这样的mysql查询 -
SELECT location,
SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0)) AS previous,
SUM(IF(action_dt_tm BETWEEN '2013-07-01' AND '2013-12-31',1,0)) AS current,
SUM(IF(action_dt_tm BETWEEN '2013-07-01' AND '2013-12-31',1,0))-
SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0)) as diff, (
SUM(IF(action_dt_tm BETWEEN '2013-07-01' AND '2013-12-31',1,0))-
SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0)))/
SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0))*100 AS percent
FROM table group by location order by percent DESC
我基于stackoverflow上的先前答案。
这个想法是返回一个位置,一个前一个日期范围计数,一个当前计数(这些范围改变),先前和当前之间的数字差异以及%增加或减少。
像 -
LOCATION 1 38 27 -11 -28.94%
LOCATION 2 6 18 12 200.00%
等
上面的代码,虽然可能很笨,但似乎有效,除了发现PREVIOUS计数为零,然后百分比返回为NULL,而不是增加/减少。
即
LOCATION 3 0 32 32 (NULL)
任何人都可以建议如何更改查询以解决此问题。
答案 0 :(得分:1)
如果您之前的值等于0,则会导致百分比列除以零。
默认情况下,除以零会产生NULL结果并且没有警告。
https://dev.mysql.com/doc/refman/5.0/en/precision-math-expressions.html
由于你有一个除零,我不确定是否有意义替换任何其他的NULL值,但你应该能够通过在进行除法之前检查前一个计数的零来替换它。
示例(将其替换为零):
SELECT location,
SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0)) AS previous,
SUM(IF(action_dt_tm BETWEEN '2013-07-01' AND '2013-12-31',1,0)) AS current,
SUM(IF(action_dt_tm BETWEEN '2013-07-01' AND '2013-12-31',1,0))-
SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0)) as diff, (
case
when (SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0))) then
0
else
SUM(IF(action_dt_tm BETWEEN '2013-07-01' AND '2013-12-31',1,0))-
SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0)))/
SUM(IF(action_dt_tm BETWEEN '2013-01-01' AND '2013-06-30',1,0))*100
end
AS percent
FROM table group by location order by percent DESC