我是PL / SQL的新手,我正试图尽可能快地学习它。
我试图做一个简单的SELECT,但我遇到了这个错误。
虽然我知道这意味着什么,但我真的不知道如何解决问题...
这是我的代码部分:
SELECT
NVL(UPPER(T.COL1),'N.D.') COL1,
V.SECO,
'N' CL_MED,
V.DEST_USO,
(CASE
WHEN V.COL2 IS NULL
AND V.SECO IN ('B090','B100') THEN ''
WHEN V.COL2 LIKE 'L-DEF%'
OR V.COL2 LIKE 'L-FUI%'
AND V.SECO IN ('B090','B100') THEN 'FUI/DEF'
WHEN V.COL2 IS NULL
AND V.SECO = 'B080'
AND V.COL3 LIKE 'DEF%'
OR V.COL3 LIKE 'FUI%' THEN 'FUI/DEF'
ELSE ''
END
) FLAG_DEF_FUI
FROM TAB1 V
JOIN TAB2 C ON (V.COL4 = C.COL4
AND V.COL5 = C.COL5
AND V.COL6 = C.COL6)
JOIN TAB3 T ON (V.COL4 = T.COL4
AND V.COL5 = T.COL5
AND V.COL5A = T.COL5A
AND T.COL6 =V.COL6)
WHERE V.COL4 = :COL4
AND V.COL6 = :COL6
AND V.COL5 NOT IN
(SELECT gcm.PDR
FROM TAB4 gcm
WHERE gcm.COL6 = :COL6
)
GROUP BY (UPPER(T.COL1),V.SECO, V.DEST_USO, FLAG_DEF_FUI)
和FLAG_DEF_FUI是导致此错误的列.....任何帮助?!
编辑:我不是在问为什么我不能在GROUP BY中使用别名。我问这个问题的解决方法......
答案 0 :(得分:2)
为了对你拥有的复杂函数进行分组,我总是进行子选择。因此,您的查询将变为:
select child_query.stuff, child_query.flag_def_fui
from
(
select
'some-stuff' some_stuff,
(case
when v.col2 is null
and v.seco in ('b090','b100') then ''
when v.col2 like 'l-def%'
or v.col2 like 'l-fui%'
and v.seco in ('b090','b100') then 'fui/def'
when v.col2 is null
and v.seco = 'b080'
and v.col3 like 'def%'
or v.col3 like 'fui%' then 'fui/def'
else ''
end
) flag_def_fui
from tab1 v
join tab2 c
on (v.col4 = c.col4
and v.col5 = c.col5
and v.col6 = c.col6)
join tab3 t
on (v.col4 = t.col4
and v.col5 = t.col5
and v.col5a = t.col5a
and t.col6 =v.col6)
where v.col4 = :col4
and v.col6 = :col6
and v.col5 not in
(select gcm.pdr
from tab4 gcm
where gcm.col6 = :col6
)
) child_query
group by child_query.stuff, child_query.flag_def_fui;
答案 1 :(得分:2)
其他答案为您提供了两个选项并且都是正确的。为了清楚明白,并且要专门回答您编辑过的问题,您有三个选项可以解决无法在 SELECT column_alias
FROM (<your query>)
GROUP BY column_alias;
中引用别名列的问题:
1)Answer 1: Wrap your query以便容易引用列别名,即
DISTINCT
2)Answer 2: Don't use GROUP BY
如果您不使用汇总功能,请改用GROUP BY
。
3)将构成列的复杂表达式复制到 SELECT CASE
WHEN col1 = 1 THEN 'one'
WHEN col1 = 2 THEN 'two'
ELSE ''
END as col1_alias,
SUM(col2) as col2_alias,
col3
FROM table_name
GROUP BY CASE
WHEN col1 = 1 THEN 'one'
WHEN col1 = 2 THEN 'two'
ELSE ''
END,
col3;
,即
target
答案 2 :(得分:1)
根据您所显示的内容,您根本不需要分组条款,因为您没有聚合函数(min,max等)。选择列表中的每一列都在group-by子句中。
如果您使用该子句来禁止重复,那么使用distinct
关键字会更简单:
SELECT DISTINCT
NVL(UPPER(T.COL1),'N.D.') COL1,
V.SECO,
'N' CL_MED,
V.DEST_USO,
(CASE
WHEN V.COL2 IS NULL
AND V.SECO IN ('B090','B100') THEN ''
WHEN V.COL2 LIKE 'L-DEF%'
OR V.COL2 LIKE 'L-FUI%'
AND V.SECO IN ('B090','B100') THEN 'FUI/DEF'
WHEN V.COL2 IS NULL
AND V.SECO = 'B080'
AND V.COL3 LIKE 'DEF%'
OR V.COL3 LIKE 'FUI%' THEN 'FUI/DEF'
ELSE ''
END
) FLAG_DEF_FUI
FROM TAB1 V
JOIN TAB2 C
ON (V.COL4 = C.COL4
AND V.COL5 = C.COL5
AND V.COL6 = C.COL6)
JOIN TAB3 T
ON (V.COL4 = T.COL4
AND V.COL5 = T.COL5
AND V.COL5A = T.COL5A
AND T.COL6 =V.COL6)
WHERE V.COL4 = :COL4
AND V.COL6 = :COL6
AND V.COL5 NOT IN
(SELECT gcm.PDR
FROM TAB4 gcm
WHERE gcm.COL6 = :COL6
)
(您可能还想查看not exists
支票是否比您现在拥有的not in
更有效。)