在另一列中重用列的结果

时间:2015-04-24 17:26:08

标签: mysql database select

如果我有查询

SELECT id,name,SUM(investments) as total_investments, SUM(investments)/10 as per_ten_investment
FROM table1
GROUP BY name

我有什么方法可以在计算per_ten_investment时使用total_investments?因此,我可以使用

而不是上述内容
SELECT id,name,SUM(investments) as total_investments, total_investments/10 as per_ten_investment
FROM table1
GROUP BY name

以上导致错误未知栏' total_investments'在'字段列表'

我遇到的问题要复杂得多,但归结为这个障碍。 谢谢大家。

2 个答案:

答案 0 :(得分:1)

一个选项是使用子查询,然后您可以引用求和字段。话虽如此,我认为您的查询没有任何问题:

SELECT id, name, total_investments, total_investments/10 per_ten_investment
FROM (SELECT id, name, SUM(investments) as total_investments
    FROM table1
    GROUP BY name) t

此外,根据您的数据,您可能希望将id字段添加到group by。 Mysql对其他人更宽容。

答案 1 :(得分:-1)

这也应该有用

SELECT id,name,SUM(investments) as total_investments, SUM(investments)/10 as per_ten_investment
FROM table1
GROUP BY name