我有两张桌子:
R_DEPT表:
DEPT_CD DEPT_NM
800 Dept A
900 Dept B
620 Dept C
R_UNIT表
UNIT_CD UNIT_NAME DEPT_CD
8120 Unit_A 800
8121 Unit_A 800
8122 Unit_A 800
9120 Unit_B 900
9126 Unit_B 900
9127 Unit_B 900
6222 Unit_C 620
6223 Unit_C 620
6234 Unit_C 620
我想要一个基于DEPT_CD键组合2个表的输出。前3个记录来自R_DEPT表,是父记录,其余记录来自R_Unit表,是子记录。每个部门都有单位。 我想首先列出所有部门(来自R_DEPT),然后列出属于每个部门的所有单位(来自R_UNIT),并且应该按部门代码(DEPT_CD)进行排序。只有在其父部门存在的情况下才应列出单位记录。 元素类型是硬编码值,具体取决于它是部门(DEP)还是单位(COA)。
这里是SQL Query所需的输出:
CLASS_ID CD NM DEPT_CD Element_Type
"Organization2" 800 Dept A <blank> "DEP"
"Organization2" 900 Dept B <blank> "DEP"
"Organization2" 620 Dept C <blank> "DEP"
"Organization2" 8120 Unit_A 800 "COA"
"Organization2" 8121 Unit_A 800 "COA"
"Organization2" 8122 Unit_A 800 "COA"
"Organization2" 9120 Unit_B 900 "COA"
"Organization2" 9126 Unit_B 900 "COA"
"Organization2" 9127 Unit_B 900 "COA"
"Organization2" 6222 Unit_C 620 "COA"
"Organization2" 6223 Unit_C 620 "COA"
"Organization2" 6234 Unit_C 620 "COA"
以下是我正在处理的查询:
Select
"Organizaton2" as CLASS_ID
DEPT_CD as CD,
DEPT_NM as NM,
UNIT_NM as DEPT_CD,
'' as ELEMENT_TYPE
FROM
(select
'Organization2' as CLASS_ID,
DEPT_CD as CD,
DEPT_SH_NM as NM,
'' as DEPT_CD,
'DEP' as ELEMENT_TYPE
FROM
R_DEPT
union All
SELECT
'Organizaton2' as CLASS_ID
, A.UNIT_CD as CD
, A.UNIT_NM as NM
, A.DEPT_CD as DEPT_CD
, 'COA' as ELEMENT_TYPE
FROM
R_UNIT A, R_DEPT B ) TABLE_ALL
WHERE A.FY = 2014 AND
A.act_fl = 1 AND
B. act_fl = 1 AND
B.DEPT_CD = A.DEPT_CD
ORDER BY A.DEPT_CD