最近,我用客户端软件PL/SQL Developer链接数据库执行一SQL语句时报:
“ORA-01791: 不是 SELECTed 表达式”
执行的SQL 如下:
select
distinct bbi.bill_no,
bbi.create_date,
bbi.notice_date ,
bboi.subject_amount ,
bboi.pay_amount ,
bbi.amount ,
bboi.order_id ,
ylhs.order_id,
ylhs.indate,
case oi.order_status
when '1' then '未支付'
when '2' then '已支付'
when '3' then '支付成功'
when '4' then '支付失败'
end as 支付结果
from yl_https_stream ylhs
right join order_info oi on ylhs.order_id =substr(oi.order_id, length(oi.order_id) - 7,8)
right join b_bill_order_info bboi on bboi.order_id = oi.order_id
right join b_bill_info bbi on bboi.bill_id = bbi.bill_id
where
bbi.bill_category = 'JX_CTCC'
and to_char(bbi.create_date, 'yyyyMMdd') >= '20120101'
and to_char(bbi.create_date, 'yyyyMMdd') <= '20130130'
order by oi.order_status desc;
原来是使用了oi.order_status 字段进行排序导致的结果
经查, SELECT语句中含有DISTINCT关键字或者有运算符时,排序用字段必须与SELECT语句中的字段相对应(也就是排序的字段要和select中所查列字段完全保持一致)
由于该select语句中使用了distinct,且oi.order_status列使用了case 语句,如果排序中只单纯用oi.order_status排序肯定会报错。
为了解决此问题,我给这个使用了case语句的字段定义个别名(别名为:支付结果), 然后将排序中换成别名即可,如:
order by 支付结果 desc
注:如果SELECT子句中出现了DISTINCT关键字,排序只能使用在select中列出的列,未列出的列不能作为排序的字段,且select中列出的列要和order by排序中的列完全一致。