错误:对于SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中

sFo*_*jit 4 postgresql

我有一个表"campaign_items",其中包含列(预算,花费),我想使用公式剩余预算计算剩余预算=预算 - 已用完

现在我在查询下运行:

select distinct a.budget,a.spent 
from campaign_items a 
where campaign_item_id=12345 
order by a.budget-a.spent
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误:

错误:对于SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中

注意:我无法DISTINCT从查询中删除关键字,因为查询是使用JdbcTemplate生成的

任何人都可以帮我解决这个错误吗?

Tim*_*sen 6

我认为错误的根本原因是您正在使用ORDER BY a.budget - a.spent,但此表达式不会出现在SELECT子句中.在下面的查询中,我使用包含计算列的子查询进行排序,但之后只选择budgetspent列.

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
Run Code Online (Sandbox Code Playgroud)