使用PARTITION
加入:
甲骨文設置:
CREATE TABLE T_EXPENDITURE ("NUMBER", "USER", "DATE", amount, dep_no) AS
SELECT 1, 'Clerk', DATE '2017-01-10', 50, 1 FROM DUAL UNION ALL
SELECT 1, 'Clerk', DATE '2017-01-15', 73, 1 FROM DUAL UNION ALL
SELECT 1, 'Clerk', DATE '2017-02-14', 13, 1 FROM DUAL UNION ALL
SELECT 2, 'Manager', DATE '2017-02-01', 150, 2 FROM DUAL;
CREATE TABLE T_ALLOWENCE (dep_no, fund) AS
SELECT 1, 2500 FROM DUAL UNION ALL
SELECT 1, 3000 FROM DUAL;
查詢:
SELECT e."NUMBER",
e."USER",
c.month,
SUM(e.amount) AS amount,
e.fund
FROM
(
SELECT e.*, a.fund
FROM t_allowance a
INNER JOIN t_expenditure e
ON (e.dep_no = a.dep_no)
) e
PARTITION BY (e."NUMBER", e."USER", e.FUND)
RIGHT OUTER JOIN
(
SELECT ADD_MONTHS(TO_DATE(:useryear || '0101', 'YYYYMMDD'), LEVEL - 1) AS month
FROM DUAL
CONNECT BY LEVEL <= 12
) c
ON(c.month <= e."DATE" AND e."DATE" < ADD_MONTHS(c.month, 1))
GROUP BY e."NUMBER", e."USER", e.FUND, c.MONTH
ORDER BY e."NUMBER", c.MONTH;
輸出:
NUMBER USER MONTH AMOUNT FUND
------ ------- ---------- ------ ----
1 Clerk 2017-01-01 123 2500
1 Clerk 2017-02-01 13 2500
1 Clerk 2017-03-01 2500
1 Clerk 2017-04-01 2500
1 Clerk 2017-05-01 2500
1 Clerk 2017-06-01 2500
1 Clerk 2017-07-01 2500
1 Clerk 2017-08-01 2500
1 Clerk 2017-09-01 2500
1 Clerk 2017-10-01 2500
1 Clerk 2017-11-01 2500
1 Clerk 2017-12-01 2500
2 Manager 2017-01-01 3000
2 Manager 2017-02-01 150 3000
2 Manager 2017-03-01 3000
2 Manager 2017-04-01 3000
2 Manager 2017-05-01 3000
2 Manager 2017-06-01 3000
2 Manager 2017-07-01 3000
2 Manager 2017-08-01 3000
2 Manager 2017-09-01 3000
2 Manager 2017-10-01 3000
2 Manager 2017-11-01 3000
2 Manager 2017-12-01 3000
查詢2:
SELECT *
FROM (
SELECT "NUMBER",
"USER",
EXTRACT(MONTH FROM "DATE") AS month,
amount,
e.dep_no,
fund
FROM T_EXPENDITURE e
INNER JOIN T_ALLOWENCE a
ON (e.dep_no = a.dep_no)
WHERE EXTRACT(YEAR FROM e."DATE") = :useryear
)
PIVOT (
SUM(amount)
FOR month IN (
1 AS Jan, 2 AS Feb, 3 AS Mar, 4 AS Apr, 5 AS May, 6 AS Jun,
7 AS Jul, 8 AS Aug, 9 AS Sep, 10 AS Oct, 11 AS Nov, 12 AS Dec
)
);
輸出:HTTP://www.orafaq使用`DBA_TABLES`以產生足夠的行
NUMBER USER DEP_NO FUND JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
------ ------- ------ ---- --- --- --- --- --- --- --- --- --- --- --- ---
1 Clerk 1 2500 123 13
2 Manager 2 3000 150
方法。 com/node/2029 –
而您正在尋找的搜索詞是「日曆表」或「日曆視圖」。 –
[如何在Oracle中填充日曆表?](http://stackoverflow.com/questions/8374959/how-to-populate-calendar-table-in-oracle) –