MySQL 2 列的百分比无效 =NULL

MySQL Percentage of 2 columns not working =NULL

我在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

其中 returns 结果如下:

**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

非常感谢 最大值

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

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

那是因为 "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

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

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

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

MySQL 然后 returns 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;