Oracle SQL查询嵌套的选择函数与连接

时间:2016-06-10 17:06:27

标签: sql oracle

我正在尝试获取包含标题“a_program,app_col,count,load_fy”的查询。试图将“a_program”设置为现有列“current_program_code”的一个非常精选的子集。 “app_col,subject_id和load_yr”是表“FT_a”中的所有现有列。现在,棘手的一点是,我只想要“FT_a”中的表格“FT_d”中不存在的响应。 “FT_a”和“FT_d”都有一个“subject_id”列。

试图运行以下内容。

select a_program, A.app_col,count(distinct A.subject_id),A.load_fy
from 
(
select A.app_col,A.subject_id, A.load_fy,

case
when A.current_program_code in ('234','ABC', 'DDD', 'TTT', 'SSS', 'PPP', 'DDM') then 'POP'
when A.current_program_code in ('AND', 'YOU', 'ARE', 'IT', 'INT','CAO','PAP') then 'ROM'
when A.current_program_code in ('ORD') then 'SAG'
when A.current_program_code in ('TO', 'SPA', 'SAP', 'SLA', 'SIS') then 'FOR'
when A.current_program_code in ('TXT', 'XLS', 'JAN') then 'FAV'
when A.current_program_code is null then 'Unknown'
else A.current_program_code
end
as a_program

from ft_a A 
left join ft_d D
on A.subject_id=D.subject_id
where D.subject_id is null
and A.load_fy='2015'
)
group by a_program, A.app_col, A.load_fy;

当我运行此代码时,我得到:

Error at Command Line:1 Column:1
Error report:
SQL Error: ORA-00904: "A"."LOAD_FY": invalid identifier
00904. 00000 -  "%s: invalid identifier"

我只能想象我在某个地方错过了一个愚蠢的逗号......有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

很难说你是否有其他问题,但我注意到的第一件事是你在外部查询中引用a别名,但a别名仅在范围内内部查询。

所以只需从外部aselect子句(SQL语句的第一行和最后一行)中删除group by别名,然后重试:

select a_program, app_col,count(distinct subject_id),load_fy
from 
(
select A.app_col,A.subject_id, A.load_fy,

case
when A.current_program_code in ('234','ABC', 'DDD', 'TTT', 'SSS', 'PPP', 'DDM') then 'POP'
when A.current_program_code in ('AND', 'YOU', 'ARE', 'IT', 'INT','CAO','PAP') then 'ROM'
when A.current_program_code in ('ORD') then 'SAG'
when A.current_program_code in ('TO', 'SPA', 'SAP', 'SLA', 'SIS') then 'FOR'
when A.current_program_code in ('TXT', 'XLS', 'JAN') then 'FAV'
when A.current_program_code is null then 'Unknown'
else A.current_program_code
end
as a_program

from ft_a A 
left join ft_d D
on A.subject_id=D.subject_id
where D.subject_id is null
and A.load_fy='2015'
)
group by a_program, app_col, load_fy;