MySQL SELECT与PDO中的子查询进行月度统计

时间:2016-08-09 13:41:18

标签: php mysql pdo

我有一个SELECT查询,用于计算每月发现的缺陷数量,然后我有另一个SELECT查询,用于计算每月修复的缺陷数量。

我正在努力将它们放在一起并计算每个月FIXED/FOUND的完成情况。

FIXED:

 SELECT 
 MAX(myCount.7)'Jul',
 MAX(myCount.8)'Aug',
 MAX(myCount.9)'Sep',
 MAX(myCount.10)'Oct',
 MAX(myCount.11)'Nov',
 MAX(myCount.12)'Dec',
 MAX(myCount.1)'Jan',
 MAX(myCount.2)'Feb',
 MAX(myCount.3)'Mar',
 MAX(myCount.4)'Apr',
 MAX(myCount.5)'May',
 MAX(myCount.6)'Jun'
 FROM (SELECT 
  COUNT(IF(month(dDateClosed) = 7,1, NULL)) '7',
  COUNT(IF(month(dDateClosed) = 8,1, NULL)) '8',
  COUNT(IF(month(dDateClosed) = 9,1, NULL)) '9',
  COUNT(IF(month(dDateClosed) = 10,1, NULL)) '10',
  COUNT(IF(month(dDateClosed) = 11,1, NULL)) '11',
  COUNT(IF(month(dDateClosed) = 12,1, NULL)) '12',
  COUNT(IF(month(dDateClosed) = 1,1, NULL)) '1',
  COUNT(IF(month(dDateClosed) = 2,1, NULL)) '2',
  COUNT(IF(month(dDateClosed) = 3,1, NULL)) '3',
  COUNT(IF(month(dDateClosed) = 4,1, NULL)) '4',
  COUNT(IF(month(dDateClosed) = 5,1, NULL)) '5',
  COUNT(IF(month(dDateClosed) = 6,1, NULL)) '6'
 FROM T_Defects INNER JOIN T_settings
 WHERE (dDateClosed >= `FYDateFROM` AND dDateClosed <= `FYDateTO`)
 GROUP BY month(dDateClosed))myCount;

实测值:

SELECT 
MAX(myCount.7)'Jul',
MAX(myCount.8)'Aug',
MAX(myCount.9)'Sep',
MAX(myCount.10)'Oct',
MAX(myCount.11)'Nov',
MAX(myCount.12)'Dec',
MAX(myCount.1)'Jan',
MAX(myCount.2)'Feb',
MAX(myCount.3)'Mar',
MAX(myCount.4)'Apr',
MAX(myCount.5)'May',
MAX(myCount.6)'Jun'
FROM (SELECT 
  COUNT(IF(month(dDateFound) = 7,1, NULL)) '7',
  COUNT(IF(month(dDateFound) = 8,1, NULL)) '8',
  COUNT(IF(month(dDateFound) = 9,1, NULL)) '9',
  COUNT(IF(month(dDateFound) = 10,1, NULL)) '10',
  COUNT(IF(month(dDateFound) = 11,1, NULL)) '11',
  COUNT(IF(month(dDateFound) = 12,1, NULL)) '12',
  COUNT(IF(month(dDateFound) = 1,1, NULL)) '1',
  COUNT(IF(month(dDateFound) = 2,1, NULL)) '2',
  COUNT(IF(month(dDateFound) = 3,1, NULL)) '3',
  COUNT(IF(month(dDateFound) = 4,1, NULL)) '4',
  COUNT(IF(month(dDateFound) = 5,1, NULL)) '5',
  COUNT(IF(month(dDateFound) = 6,1, NULL)) '6'
FROM T_Defects INNER JOIN T_settings
WHERE (dDateFound >= `FYDateFROM` AND dDateFound <= `FYDateTO`)
GROUP BY month(dDateFound))myCount;

1 个答案:

答案 0 :(得分:0)

将它们全部放在一个大表中,其中包含FOUND列,FIXED列和每月比率fixed/found的列

SELECT 
 MAX(myCount.7_found)'Jul_found',
 MAX(myCount.8_found)'Aug_found',
 ...
 MAX(myCount.7_fixed)'Jul_fixed',
 MAX(myCount.8_fixed)'Aug_fixed',
...
 MAX(myCount.7_fixed)/MAX(myCount.7_found) 'Jul_completion'
 MAX(myCount.8_fixed)/MAX(myCount.8_found) 'Aug_completion'
...

FROM (SELECT 
  COUNT(IF(month(dDateFound) = 7,1, NULL)) '7_found',
  COUNT(IF(month(dDateFound) = 8,1, NULL)) '8_found',
 ...
  COUNT(IF(month(dDateClosed) = 7,1, NULL)) '7_fixed',
  COUNT(IF(month(dDateClosed) = 8,1, NULL)) '8_fixed',
...