MySql,SELECT列表不在GROUP BY子句中,并且包含非聚合列

时间:2016-08-18 14:30:15

标签: mysql

我正在使用MySql 5.7,我在此查询中收到错误:

  SELECT 
    COUNT(id) AS sales,
    SUM(amount) AS total,
    created 
  FROM
    `payments` 
  WHERE status =1
  GROUP BY MONTH(created);

如果我改变GROUP BY MONTH(created) 用:

GROUP BY created

然后错误就消失了。我无权访问my.ini,对sql_mode进行更改。

1 个答案:

答案 0 :(得分:1)

由于您按月分组,因此您还要输出月份

  SELECT COUNT(id) AS sales,
         SUM(amount) AS total,
         MONTH(created)
  FROM payments 
  WHERE status = 1
  GROUP BY MONTH(created)

否则MySQL必须从组中选择created值。但是你应该定义要显示的内容。

另一种可能性而不是输出MONTH(created)将是min(created)之类的日期的聚合,它会输出每个月的最早日期。