GROUP_CONCAT或SUM与里面的Count(*)和MySQL中的GROUP BY

时间:2013-12-19 15:39:09

标签: mysql sql group-by concat group-concat

我目前有这个查询:

SELECT ((count(*) DIV 20) * 10) AS money_earned 
FROM ticket 
WHERE 
    closed_by = 269 AND 
    status = 1 AND
    closed_index >= TO_DAYS("2012/01/01") AND closed_index <= TO_DAYS("2013/01/01")
GROUP BY closed_index;

它产生了这个:

money_earned

60
50
30
20
20

有没有办法对这些行求和,或将结果行连接成一个字符串。我试图使用GROUP_CONCAT,但得到“无效使用组函数”错误。

相反,如果可能的话,我想在单个查询中产生以下内容:

money_earned
180

money_earned
60,50,30,20,20

1 个答案:

答案 0 :(得分:2)

您可以将查询用作子查询:

select sum(money_earned), group_concat(money_earned)
from (SELECT ((count(*) DIV 20) * 10) AS money_earned 
      FROM ticket 
      WHERE closed_by = 269 AND 
            status = 1 AND
            closed_index >= TO_DAYS("2012/01/01") AND closed_index <= TO_DAYS("2013/01/01")
      GROUP BY closed_index
     ) tci;

由于四舍五入,我会谨慎地在一个查询中执行此操作。