0

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

问候,

4

2 回答 2

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
于 2013-07-24T12:49:35.050 回答
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

在这里演示

于 2013-07-24T13:01:32.417 回答