我需要帮助理解为什么我不能在使用CASE
的选择列表中使用GROUP BY字段这是查询
select
CASE WHEN COUNT(AB9_NUMOS) = 0 THEN 'P' ELSE 'E' END AS result,
AAG_DESCRI,
count(AB6_STATUS) as count
from AB6010
left join AB7010 on AB7_FILIAL = AB6_FILIAL and AB7_NUMOS = AB6_NUMOS and AB7010.D_E_L_E_T_ = ' '
left join AAG010 on AAG_CODPRB = AB7_CODPRB and AAG010.D_E_L_E_T_ = ' '
left join AB9010 on AB9_FILIAL = AB6_FILIAL AND AB9_NUMOS = AB6_NUMOS+'01' and AB9010.D_E_L_E_T_ = ' '
where
ab6010.D_E_L_E_T_ = ' '
and AB6_FILIAL = '01'
and AB6_STATUS = 'A'
group by result, AAG_DESCRI
在此查询中,我正在尝试对表AB6010中的行进行分类, AB6010(服务订单)中的每一行在AB9010上都可以没有或N个引用(如果我的AB6010行在AB9010中有任何引用意味着我的服务订单已经被执行)。所以我要做的是:
如果AB6010在AB9010中有0个引用,则其状态为“P”
如果AB6010在AB9010中有1个或多个引用,则其状态应为“E”
然后我想按此状态进行分组,并按AAG_DESCRI(这意味着它是哪种服务顺序)进行分组,并显示有多少AB6010类型X(aag_descri)行是'P',有多少是'E' ”。但是当我运行查询时,我收到以下错误
Invalid column name 'result'.
我的预期结果应该是
result AAG_DESCRI count
---------- ------------------------------ -----------
E CORTE A PLASMA 7
E CORTE E DOBRA 31
E FABRICACAO 7
E MANUTENCAO 4
E RETORNO/GARANTIA 3
P CORTE A PLASMA 3
P CORTE E DOBRA 10
P FABRICACAO 3
P MANUTENCAO 1
P RETORNO/GARANTIA 8
答案 0 :(得分:1)
您可以从以下cte
中受益。
;with cte (result,AB6_NUMOS,AAG_DESCRI) as (
select
CASE WHEN COUNT(AB9_NUMOS) = 0 THEN 'P' ELSE 'E' END AS result,
AB6_NUMOS,
AAG_DESCRI
from AB6010
left join AB7010 on AB7_FILIAL = AB6_FILIAL and AB7_NUMOS = AB6_NUMOS and AB7010.D_E_L_E_T_ = ' '
left join AAG010 on AAG_CODPRB = AB7_CODPRB and AAG010.D_E_L_E_T_ = ' '
left join AB9010 on AB9_FILIAL = AB6_FILIAL AND AB9_NUMOS = AB6_NUMOS+'01' and AB9010.D_E_L_E_T_ = ' '
where
ab6010.D_E_L_E_T_ = ' '
and AB6_FILIAL = '01'
and AB6_STATUS = 'A'
group by AB6_NUMOS,AAG_DESCRI
)
select result, AAG_DESCRI, count(AB6_NUMOS) as count
from cte
group by result, AAG_DESCRI
order by result,AAg_DESCRI
答案 1 :(得分:1)
使用子查询
select
from (select AAG_DESCRI, COUNT(AB9_NUMOS) as c1, COUNT(AB6_STATUS) as c2
, CASE WHEN COUNT(AB9_NUMOS) = 0 THEN 'P' ELSE 'E' END AS result
from from AB6010
group by AAG_DESCRI
) t