MySQL sum()和group by

时间:2010-12-30 20:23:39

标签: sql mysql group-by

我有以下查询:

SELECT 
   corporation.id, expense.year, expense.type, SUM(Expense.amount) as sum 
FROM 
   expenses 
LEFT JOIN
   corporation ON expense.corporation_id = corporation.id
LEFT JOIN
   project ON expense.project_id = project.id
WHERE
   project.id = XYZ
GROUP BY
   corporation.name, corporation.id, expense.year
ORDER BY
   sum DESC;

MySQL现在通过sum订购最新的费用。但是我希望按所有年份的sum订购(例如,不包含GROUP BY (...) expense.year的查询)。这可能吗?

1 个答案:

答案 0 :(得分:0)

Sum是单个值,因此您可以使用一个查询来获取它。并在单独查询中获取其他数据。或使用SUM(...) as sum

上的子查询