MySQL的2列不工作的百分比= NULL

时间:2015-08-18 15:24:03

标签: mysql sql multiple-columns percentage

我在MYSQL中有以下声明:

SELECT Site, Areateam, 
SUM( IF( year = '15-16', 1, 0 ) ) "Y2", 
SUM( IF( year = '14-15', 1, 0 ) ) "Y1",
SUM('Y2') / SUM('Y1')* 100 AS Diff
FROM CD2015_EmailIncidents
WHERE Areateam = 'Greater Manchester'
GROUP BY Site

返回以下结果:

**Site           |Areateam             |Y2  |Y1  |Diff**

Acute Trust      |Greater Manchester   |0   |1   |NULL

Care Home        |Greater Manchester   |3   |22  |NULL

CD Store Room    |Greater Manchester   |7   |4   |NULL

College Greater  |Greater Manchester   |0   |1   |NULL

我似乎无法用正确的语法显示Y2和Y1之间的百分比差异,因为它一直显示NULL

非常感谢 最大

3 个答案:

答案 0 :(得分:0)

您无法在select子句中使用计算列名称。首先乘以100以避免整数限制

SUM(year = '15-16') * 100 / SUM(year = '14-15')  AS Diff

答案 1 :(得分:0)

这是因为“Y1”和“Y2”在该情境中不存在。

SELECT Site, Areateam, 
    SUM( IF( year = '15-16', 1, 0 ) ) "Y2", 
    SUM( IF( year = '14-15', 1, 0 ) ) "Y1",
    SUM( IF( year = '15-16', 1, 0 ) ) * 100 / 
    SUM( IF( year = '14-15', 1, 0 ) AS Diff
FROM CD2015_EmailIncidents
WHERE Areateam = 'Greater Manchester'
GROUP BY Site

点击此处查看四舍五入ROUND OR TRUNC

答案 2 :(得分:0)

你的问题是你正在对字符串值进行算术运算:

SUM('Y2') / SUM('Y1')* 100 AS Diff

MySQL执行静默转换,因此它将值转换为数字。没有前导数字,因此它们被转换为0。

MySQL然后为NULL返回0/0

Juergen有正确的解决方案。您的整体查询可表示为:

SELECT Site, Areateam, 
       SUM(year = '15-16') as Y2, 
       SUM(year = '14-15') as Y1,
       100 * SUM(year = '15-16') / SUM(year = '14-15') AS Diff
FROM CD2015_EmailIncidents
WHERE Areateam = 'Greater Manchester'
GROUP BY Site;