表别名在oracle中的子查询中不起作用

时间:2017-09-24 10:54:15

标签: sql oracle select subquery alias

我使用sum聚合函数和子查询生成记录,但别名在内部查询中不起作用。 我的查询是

    select UPP.item_total, 
           (select sum(INN.item_value_afs) total_item_value_afs from 
              (select distinct INN.reg_no,INN.tpt_cuo_nam,INN.item_total,INN.item_value_afs
                  from sigtasad.customs_import_data INN where INN.reg_no=UPP.reg_no and INN.tpt_cuo_nam=UPP.tpt_cuo_nam))    total_item_value,   
     sum(UPP.code_tax_amount), UPP.cmp_nam from SIGTASAD.CUSTOMS_IMPORT_DATA UPP where
 UPP.reg_no='38699' and UPP.company_tin='9003247336' group by        
UPP.reg_no,UPP.tpt_cuo_nam,UPP.cmp_nam,UPP.item_total ; 

此查询生成此错误: ORA-00904:" UPP"。" TPT_CUO_NAM":无效标识符

我想要这样的结果!!!

enter image description here

2 个答案:

答案 0 :(得分:0)

您的查询有很多错误和不良习惯。例如:

  • 使用未定义的表别名限定列名称。
  • 您按不在select
  • 中的列进行汇总
  • 您在具有sum()
  • 的子查询上使用sum()

根据您展示的图片,您可能想要这样的内容:

select upp.item_total,
       sum(item_value_afs) as total_item_value,
       sum(upp.code_tax_amount),
       upp.cmp_nam
from SIGTASAD.CUSTOMS_IMPORT_DATA upp
where upp.reg_no = '38699' and upp.company_tin = '9003247336'
group by upp.cmp_nam, upp.item_total ;

或者也许:

select upp.item_total,
       sum(sum(item_value_afs)) over (partition by upp.cmp_nam, upp.item_total) as total_item_value,
       sum(upp.code_tax_amount),
       upp.cmp_nam
from SIGTASAD.CUSTOMS_IMPORT_DATA upp
where upp.reg_no = '38699' and upp.company_tin = '9003247336'
group by upp.cmp_nam, upp.item_total ;

答案 1 :(得分:0)

你最里面的子查询

(select distinct nn.reg_no,inn.tpt_cuo_nam, inn.item_total, inn.item_value_afs
 from sigtasad.customs_import_data inn
 where inn.reg_no = upp.reg_no and inn.tpt_cuo_nam = upp.tpt_cuo_nam
)

引用未加入的表(upp)。它也没有别名,但问题会在以后出现。请注意,似乎还有nn.reg_no类型而不是inn.reg_no

这里没有显示表格的结构,但修复问题意味着:

(select distinct inn.reg_no,inn.tpt_cuo_nam, inn.item_total, inn.item_value_afs
 from sigtasad.customs_import_data inn, SIGTASAD.CUSTOMS_IMPORT_DATA upp
 where inn.reg_no = upp.reg_no and inn.tpt_cuo_nam = upp.tpt_cuo_nam
)