在MYSQL中计算查询结果

时间:2013-04-27 11:39:48

标签: mysql count

我运行了以下MYSQL查询:

   SELECT TIMESTAMPDIFF(MONTH,`original_date`, `last_modified_date`) 
   FROM `ft2_form_1` 
   WHERE `success` LIKE '1' 
   AND `color` LIKE '1'

这会返回一系列数字,如下所示: 五 五 五 6 7 7 7 五 6

我想计算返回值,所以结果看起来像这样

    |  value  |   count  |
    ----------------------
    |       5 |        4 |
    |       6 |        2 |
    |       7 |        3 |

如何修改查询以返回这些结果?

2 个答案:

答案 0 :(得分:2)

试试这个

SELECT t.value,  COUNT(t.value) FROM
(
       SELECT TIMESTAMPDIFF(MONTH,`original_date`, `last_modified_date`) AS value
       FROM `ft2_form_1` 
       WHERE `success` LIKE '1' 
       AND `color` LIKE '1'
) t
GROUP BY t.value

OR

   SELECT 
      TIMESTAMPDIFF(MONTH,`original_date`, `last_modified_date`) AS value, COUNT(*)
   FROM `ft2_form_1` 
   WHERE `success` LIKE '1' 
   AND `color` LIKE '1'
   GROUP BY TIMESTAMPDIFF(MONTH,`original_date`, `last_modified_date`)

答案 1 :(得分:0)

您可以尝试此查询

SELECT table.value,  COUNT(table.value) FROM
(
    SELECT TIMESTAMPDIFF(MONTH,`original_date`, `last_modified_date`) AS value
    FROM `ft2_form_1`        
        WHERE `success` LIKE '1' 
        AND `color` LIKE '1'
) table
GROUP BY table.value;