如果对多个列应用排序依据,则不对计算列进行排序

时间:2019-07-03 06:24:42

标签: postgresql

我正在使用PostgreSQL版本9.6。我想在具有一个现有列的计算列上应用订单。如果我仅对计算列应用订单,那么它可以正常工作,但在order by子句中再添加一列时,则会抛出错误。

错误是:

ERROR:  column "column_name" does not exist

以下是查询:

创建表:

CREATE TABLE "student" (
    "age" numeric(2) NOT NULL ,
    "name" varchar(128) NOT NULL);

插入数据

insert into student values(22, 'Vikram');
insert into student values(12, 'Bhagirath');
insert into student values(12, 'SKR');

查询:

Select *, 
       CASE WHEN age>18 then 'Adult' ELSE 'MINOR' end  as category 
from student 
order by category;

上面的查询工作正常。如果我将name添加到order by子句,则会抛出错误:

Select *, 
       CASE WHEN age>18 then 'Adult' ELSE 'MINOR' end  as category 
from student order by (category,name);

错误:

ERROR:  column "category" does not exist

1 个答案:

答案 0 :(得分:1)

删除-1列周围的括号:

group by

在线示例:https://rextester.com/BHQ36816

相关问题