我有一个表“campaign_items”,其中包含列(预算,花费),我想使用公式计算剩余预算 剩余预算=预算 - 花费
现在我在查询下运行:
select distinct a.budget,a.spent
from campaign_items a
where campaign_item_id=12345
order by a.budget-a.spent
但我收到错误:
错误:对于SELECT DISTINCT,ORDER BY表达式必须出现在选择列表
中
注意:我无法从查询中删除DISTINCT
关键字,因为查询是使用JdbcTemplate生成的
有人可以帮我解决这个错误吗?
答案 0 :(得分:6)
我认为错误的根本原因是您使用ORDER BY a.budget - a.spent
进行排序,但此表达式未出现在SELECT
子句中。在下面的查询中,我使用包含计算列的子查询进行排序,但只选择budget
和spent
列。
select t.budget, t.spent
from
(
select distinct a.budget,
a.spent,
a.budget - a.spent as sort,
from campaign_items a
where campaign_item_id = 12345
) t
order by t.sort