mysql交叉号错误总和

时间:2013-07-24 12:41:29

标签: mysql stored-procedures

我在mysql交叉表中有一个问题总和。

我的编码如下:

 SELECT IFNULL(Prtype,''Total'') as Prtype,sum(t.data) AS Total,',
 SUM(IF(office ='A',`data`, NULL)) AS 'A',
 SUM(IF(office ='B',`data`, NULL)) AS 'B',
 SUM(IF(office ='C',`data`, NULL)) AS 'C',
 FROM((SELECT Prtype, office,`data` as data
 FROM TBLGETDATAALL_1 GROUP BY office,Prtype,data) t) GROUP BY Prtype

问题是所有办公室的总和不等于。

Simple data:

Type    Total   A   B   C
P1          3   2   1   1
P2          6   2   2   1
P3          6   3   1   1


Simple data 2:

Total: 50,455

(1,333  1,352   1,216   2,127   1,520   2,700   1,174   1,250   2,458   1,374   2,877   970 2,458   2,930   1,365   2,655   1,184   3,001   2,421   2,689   2,220   1,590   2,678   2,212   1,329)=49083

why total=50,455 and sum each office=49083 ?

---------
table name
Prtype    office  data
 p1         A     2
 P2         B     3
 P3         C     1
 ...   ...     ....    ....
----------

此致

2 个答案:

答案 0 :(得分:0)

使用0代替null

 SELECT IFNULL(Prtype,''Total'') as Prtype,sum(t.data) AS Total,',
 SUM(IF(office ='A',`data`, 0)) AS 'A',
 SUM(IF(office ='B',`data`, 0)) AS 'B',
 SUM(IF(office ='C',`data`, 0)) AS 'C',
 FROM((SELECT Prtype, office,`data` as data
 FROM TBLGETDATAALL_1 GROUP BY office,Prtype,data) t) GROUP BY Prtype

答案 1 :(得分:0)

试试这个

      select Prtype , A , B , C , sum( A +B +C) as total from (
      SELECT IFNULL(Prtype,'Total') as Prtype ,
      SUM(IF(office ='A',`data`, 0)) AS A,
      SUM(IF(office ='B',`data`, 0)) AS B,
      SUM(IF(office ='C',`data`, 0)) AS C
      FROM TBLGETDATAALL_1
      GROUP BY Prtype ) t
      GROUP BY Prtype

DEMO HERE