迷失在SQL查询中

时间:2012-03-15 09:07:37

标签: sql db2

我尝试在各级军官中产生头衔,但我只获得更详细的头衔。我该如何纠正这个陈述?

目前,我获得了更详细的标题,如99ABC,但我想获得所有组合。

99---
99--C
99-B-
99A--
99-BC
99A-C
99AB-
99ABC


  select distinct TITLE 
   from (SELECT         
        (case when OFF3.OFFICER_ID IS NOT NULL then DEP.INDICATOR || TEA.INDICATOR || coalesce( OFF1.INDICATOR, '-') || 
        coalesce( OFF2.INDICATOR, '-') || coalesce( OFF3.INDICATOR, '-') 
        else case when OFF2.OFFICER_ID IS NOT NULL then DEP.INDICATOR || TEA.INDICATOR || coalesce( OFF1.INDICATOR, '-') || coalesce( OFF2.INDICATOR, '-') || '-' 
        else case when OFF1.OFFICER_ID IS NOT NULL then DEP.INDICATOR || TEA.INDICATOR || coalesce( OFF1.INDICATOR, '-') || '--' 
        else DEP.INDICATOR || TEA.INDICATOR || '---' end end end ) as TITLE 

        FROM DEPARTMENT DEP, 
        TEAM TEA 
        LEFT OUTER JOIN OFFICER OFF1 ON OFF1.OFFICER1_TEAM_ID = TEA.TEAM_ID 
        LEFT OUTER JOIN OFFICER OFF2 ON OFF2.OFFICER2_TEAM_ID = TEA.TEAM_ID 
        LEFT OUTER JOIN OFFICER OFF3 ON OFF3.OFFICER3_TEAM_ID = TEA.TEAM_ID 

        WHERE TEA.TEAM_DEPA_ID = DEP.DEPARTMENT_ID 
            AND TEA.TEAM_MANAGER_ID IS NOT NULL 
            AND coalesce( TEA.TEAM_MANAGER_ID, OFF1.TEAM_OFFICER_ID, OFF2.TEAM_OFFICER_ID, OFF3.TEAM_OFFICER_ID ) is not null ) myselect

P.S。 ||用于概念操作。

1 个答案:

答案 0 :(得分:1)

(编辑,删除CTE)尝试:

select distinct TITLE from 
(SELECT case title_case
             when 0 then TITLE0
             when 1 then TITLE1
             when 2 then TITLE2
             when 3 then TITLE3
        end as TITLE
 FROM
    (SELECT 0 title_case FROM sysibm.sysdummy1 UNION ALL
     SELECT 1 title_case FROM sysibm.sysdummy1 UNION ALL
     SELECT 2 title_case FROM sysibm.sysdummy1 UNION ALL
     SELECT 3 title_case FROM sysibm.sysdummy1) tc
    CROSS JOIN 
    (SELECT case when OFF3.OFFICER_ID IS NOT NULL 
                      then DEP.INDICATOR || TEA.INDICATOR || coalesce( OFF1.INDICATOR, '-') || coalesce( OFF2.INDICATOR, '-') || coalesce( OFF3.INDICATOR, '-') 
            end as TITLE3,
            case when OFF2.OFFICER_ID IS NOT NULL 
                      then DEP.INDICATOR || TEA.INDICATOR || coalesce( OFF1.INDICATOR, '-') || coalesce( OFF2.INDICATOR, '-') || '-' 
            end as TITLE2,
            case when OFF1.OFFICER_ID IS NOT NULL 
                      then DEP.INDICATOR || TEA.INDICATOR || coalesce( OFF1.INDICATOR, '-') || '--' 
            end as TITLE1,
            DEP.INDICATOR || TEA.INDICATOR || '---' as TITLE0
     FROM DEPARTMENT DEP
     JOIN TEAM TEA ON TEA.TEAM_DEPA_ID = DEP.DEPARTMENT_ID 
     LEFT JOIN OFFICER OFF1 ON OFF1.OFFICER1_TEAM_ID = TEA.TEAM_ID 
     LEFT JOIN OFFICER OFF2 ON OFF2.OFFICER2_TEAM_ID = TEA.TEAM_ID 
     LEFT JOIN OFFICER OFF3 ON OFF3.OFFICER3_TEAM_ID = TEA.TEAM_ID 
     WHERE TEA.TEAM_MANAGER_ID IS NOT NULL 
    ) mytitles
) myselect