如何在不设置 sql 模式的情况下使用 mysql 中的分组进行聚合?

How do I aggregate with group by in mysql withou setting sql mode?

这个查询得到了我想要的输出。为了 运行 它我必须 运行

SET sql_mode = '';

否则我会得到一个错误:

SELECT 列表不在 GROUP BY 子句中并且包含非聚合列 'knownLoss.t1.loss',它在功能上不依赖于 GROUP BY 子句中的列;这与 sql_mode=only_full_group_by

不兼容
SELECT 
  t1.klDate AS LDate
  , t1.Category
  , t1.reason AS Reason
  , sum(t1.loss) AS Loss
  , round(t1.loss / t2.loss,2) AS Percentage
FROM 
  deptkl t1
JOIN (
  SELECT 
      Store
    , sum(loss) AS loss
  FROM
    deptkl
  WHERE 
    klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
AND 
    klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
AND
    Store = 19
AND
    Department = 80
) t2 ON t1.Store = t2.Store

WHERE 
  klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
  AND 
  klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
  AND
  t1.Store = 19
AND
  Department = 80
GROUP BY
  klDate
, Category
, reason

当我将它放入 Jasper Studio 的数据集和查询对话框中时,我得到了同样的错误并且我无法使用 SET sql_mode = '';命令。有什么想法吗?如果有一种方法可以不使用 SET sql_mode = '';?

我猜错误出在您 select:

中的这一行
round(t1.loss / t2.loss,2) AS Percentage

由于您的 GROUP BY 子句不包含此列,因此有点像掷硬币,将使用 t1.losst2.loss 值。在某些情况下,根据您的标准,这些值恰好总是相同的,因此无论如何您都会得到正确的结果,但是数据库仍然会抱怨,因为它被要求 return 这些列的结果有点武断。处理此问题的一种方法是简单地将聚合函数应用于相关列,如下所示:

round(min(t1.loss) / min(t2.loss),2) AS Percentage

或...

round(avg(t1.loss) / avg(t2.loss),2) AS Percentage

我想你想这样做:

round(sum(t1.loss / t2.loss)/count(*),2)  AS Percentage

这将计算结果中每条记录的平均损失总和,然后将其除以该组记录的计数,就像平均值的平均值。

编辑:

sorry i made a syntax error now ,it should give the th wanted result and the error is because you are not using aggregate function on a column that is not in group by clause