请你帮我从下面的sql代码创建动态sql。
select *
from (SELECT U.ODF_PARENT_ID PROJECT_ID,
U.ID UNIT_ID,
COUNTRY_OBS.OBS_UNIT_ID,
SUM(NVL(SLICE,0)) SLICE,
TO_CHAR(SLICE_DATE,'MON YY') Month_label
FROM ODF_SL_5019059,
ODF_CA_PPD_UNIT_FORECAST UF,
ODF_CA_PPD_UNIT U,
NBI_DIM_OBS COUNTRY_OBS
WHERE SLICE_REQUEST_ID=5005021
AND PRJ_OBJECT_ID = UF.ID
AND UF.ODF_PARENT_ID=U.ID
AND U.ODF_PARENT_ID = 5131001
AND UF.PPD_COUNTRY=COUNTRY_OBS.OBS_UNIT_ID
--AND TRUNC(SLICE_DATE,'MONTH') >= TRUNC(SYSDATE,'MONTH')
AND TRUNC(SLICE_DATE,'YEAR') = TRUNC(SYSDATE,'YEAR')
GROUP BY U.ODF_PARENT_ID,
U.ID,
COUNTRY_OBS.OBS_UNIT_ID,
TO_CHAR(SLICE_DATE,'MON YY')
) main
pivot (sum(SLICE)
for MONTH_LABEL IN ('Jan 00' , 'Feb 00', 'Apr 18'))
我无法转换它。
请指导我。
感谢。
答案 0 :(得分:1)
我不确定什么应该是动态的,我不太确定如何使用它。但是,下面是构建动态SQL语句的一种方法。
declare
l_query VARCHAR2(4000);
L_SLICE_REQUEST_ID NUMBER;
L_ODF_PARENT_ID NUMBER;
begin
SELECT ODF_PARENT_ID
INTO L_ODF_PARENT_ID
FROM TABLE;
SELECT SLICE_REQUEST_ID
INTO L_SLICE_REQUEST_ID
FROM TABLE;
l_query := q'#
select *
from (SELECT U.ODF_PARENT_ID PROJECT_ID,
U.ID UNIT_ID,
COUNTRY_OBS.OBS_UNIT_ID,
SUM(NVL(SLICE,0)) SLICE,
TO_CHAR(SLICE_DATE,'MON YY') Month_label
FROM ODF_SL_5019059,
ODF_CA_PPD_UNIT_FORECAST UF,
ODF_CA_PPD_UNIT U,
NBI_DIM_OBS COUNTRY_OBS
WHERE SLICE_REQUEST_ID=[[L_SLICE_REQUEST_ID]]
AND PRJ_OBJECT_ID = UF.ID
AND UF.ODF_PARENT_ID=U.ID
AND U.ODF_PARENT_ID = [[L_ODF_PARENT_ID]]
AND UF.PPD_COUNTRY=COUNTRY_OBS.OBS_UNIT_ID
AND TRUNC(SLICE_DATE,'YEAR') = TRUNC(SYSDATE,'YEAR')
GROUP BY U.ODF_PARENT_ID,
U.ID,
COUNTRY_OBS.OBS_UNIT_ID,
TO_CHAR(SLICE_DATE,'MON YY')
) main
pivot (sum(SLICE)
for MONTH_LABEL IN ('Jan 00' , 'Feb 00', 'Apr 18'));
#';
l_query := REPLACE(l_query, '[[L_SLICE_REQUEST_ID]]', L_SLICE_REQUEST_ID);
l_query := REPLACE(l_query, '[[L_ODF_PARENT_ID]]', L_ODF_PARENT_ID);
<<Execute the l_query variable>>
END;