我为作业完成了以下代码:
DECLARE
Ledger_rec DDI.LEDGER_VIEW%ROWTYPE;
PROCEDURE Var2Count(v_col IN NUMBER)
IS
BEGIN
DBMS_OUTPUT.PUT(TO_CHAR(NVL(v_col,0), '999,999'));
END;
BEGIN
DBMS_OUTPUT.PUT_LINE(' Total Head Count by Registration Date');
DBMS_OUTPUT.NEW_LINE;
DBMS_OUTPUT.PUT_LINE('REGDATE 101 102 103 104 105 106 107 108');
DBMS_OUTPUT.PUT_LINE('-------- ----- ----- ----- ----- ----- ----- ----- -----');
FOR Ledger_rec IN
(
SELECT * FROM
(
SELECT REGDATE, ADULTCNT, CHILDCNT, ROOMNUM
FROM DDI.LEDGER_VIEW
)
PIVOT
(
SUM(CHILDCNT + ADULTCNT)
FOR ROOMNUM IN ('101' AS r101,
'102' AS r102,
'103' AS r103,
'104' AS r104,
'105' AS r105,
'106' AS r106,
'107' AS r107,
'108' AS r108)
)
ORDER BY REGDATE
)
LOOP
DBMS_OUTPUT.PUT(RPAD(Ledger_rec.REGDATE, 16));
Var2Count(Ledger_rec.r101);
Var2Count(Ledger_rec.r102);
Var2Count(Ledger_rec.r103);
Var2Count(Ledger_rec.r104);
Var2Count(Ledger_rec.r105);
Var2Count(Ledger_rec.r106);
Var2Count(Ledger_rec.r107);
Var2Count(Ledger_rec.r108);
DBMS_OUTPUT.NEW_LINE;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No data found.');
END;
这是有效的,除了我在分配说明中遗漏了一件事:
使用动态变量(CHILDCNT + ADULTCNT)HEADCNT 总和SUM(HEADCNT)
所以,我认为我的代码应该是SUM(HEADCNT)
。如何分配和使用此动态变量?
答案 0 :(得分:1)
您可以在第一个圆括号内定义HEADCNT
并重复使用。
SELECT * FROM
(
SELECT REGDATE, ADULTCNT, CHILDCNT, CHILDCNT + ADULTCNT HEADCNT, ROOMNUM
FROM DDI.LEDGER_VIEW
)
PIVOT
(
SUM(HEADCNT)
FOR ROOMNUM IN ('101' AS r101,
'102' AS r102,
'103' AS r103,
'104' AS r104,
'105' AS r105,
'106' AS r106,
'107' AS r107,
'108' AS r108)
)
ORDER BY REGDATE