Oracle SQL - 输出结果不是具有合并的预期输出

时间:2018-02-07 06:30:11

标签: sql oracle

我遇到了以下问题。

这是我预期的结果:

image path

但这是我得到的结果:

image path

编码;

SELECT CVRGVEHICLEID
       , LISTAGG(COALESCE(WIND1,',')
                || COALESCE(NAMEDDRIV1,',')
                || COALESCE(LLPGER1,',')
                || COALESCE(PERIL1,',')
                || COALESCE(SRCC1,',')
                || COALESCE(CART1,',')
                || COALESCE(OTHITEM1,',')) 
       WITHIN GROUP (ORDER BY CVRGVEHICLEID) FLAG
FROM(
    SELECT CH_MOTOR_CAMP_BASE.CVRGVEHICLEID,
           CASE WHEN ADDON_WIND <> '0' THEN 'WIND' END WIND1,
           CASE WHEN ADDON_NAMEDDRIV <> '0' THEN 'NAMEDDRIV' END NAMEDDRIV1,
           CASE WHEN ADDON_LLPGER <> '0' THEN 'LLPGER' END LLPGER1,
           CASE WHEN ADDON_PERIL <> '0' THEN 'PERIL' END PERIL1,
           CASE WHEN ADDON_SRCC <> '0' THEN 'SRCC' END SRCC1,
           CASE WHEN ADDON_CART <> '0' THEN 'CART' END CART1,
           CASE WHEN ADDON_OTHITEM <> '0' THEN 'OTHITEM' END OTHITEM1
    FROM CH_MOTOR_CAMP_BASE, CH_MOTCAMP_VEHITEM_TRANS
    WHERE CH_MOTOR_CAMP_BASE.CVRGVEHICLEID = CH_MOTCAMP_VEHITEM_TRANS.CVRGVEHICLEID (+)
    )
GROUP BY CVRGVEHICLEID;

1 个答案:

答案 0 :(得分:0)

LISTAGG用于跨多行连接同一列中的值。您似乎正在尝试连接每个记录的多个列,并在填充列之间使用一些格式(逗号)。

我建议您尝试这样的事情,它只使用连接运算符和nvl2()来测试前一列是否已填充,因此下一个列需要逗号。它还会生成'-- NO ADDON --'标志。

select cvrgvehicleid
       , case 
            when noaddon1 is not null then noaddon1
            else rtrim(
                 wind1
                 || nvl2(wind1, ',', null) || nameddriv1
                 || nvl2(nameddriv1, ',', null) || llpger1
                 || nvl2(llpger1, ',', null) || peril1
                 || nvl2(peril1, ',', null) || srcc1
                 || nvl2(srcc1, ',', null) || cart1
                 || nvl2(cart1, ',', null) || othitem1
                  , ',')
         end flag
from(
    select ch_motor_camp_base.cvrgvehicleid,
           case when addon_wind <> '0' then 'WIND' end wind1,
           case when addon_nameddriv <> '0' then 'NAMEDDRIV' end nameddriv1,
           case when addon_llpger <> '0' then 'LLPGER' end llpger1,
           case when addon_peril <> '0' then 'PERIL' end peril1,
           case when addon_srcc <> '0' then 'SRCC' end srcc1,
           case when addon_cart <> '0' then 'CART' end cart1,
           case when addon_othitem <> '0' then 'OTHITEM' end othitem1,
           case when addon_wind = '0' 
               and addon_nameddriv = '0' 
               and addon_llpger = '0' 
               and addon_peril = '0' 
               and addon_srcc = '0' 
               and addon_cart = '0' 
               and addon_othitem  '0' then '-- NO ADDON --' end noaddon1
    from ch_motor_camp_base, ch_motcamp_vehitem_trans
    where ch_motor_camp_base.cvrgvehicleid = ch_motcamp_vehitem_trans.cvrgvehicleid (+)
    )
group by cvrgvehicleid;

注意:未经测试,因为您没有提供样本测试数据。您的实际情况有点不清楚,因此猜测原始数据的风险太大。