我在外部查询和内部查询中都有一个SUM
聚合函数,这需要在外部查询或内部查询中最小化到一个SUM
函数。我应该group by item, loc, dur, startdate
,因为我会得到重复的值。
我尝试使用WITH
子句,但是没有用。有人告诉我,我可以使用row_Number
分析函数来解决此问题,但在这里不知道如何使用。
L_Week_Start_Date = TO_DATE('02/DEC/2018', 'DD/MOM/YYYY')
SELECT Item,
Loc,
Dur,
StartDate,
SUM(P1) P1,
SUM(P8) P8,
SUM(P15) P15,
SUM(P22) P22
FROM
(SELECT DISTINCT SkuXFcst.Item Item,
SkuXFcst.Loc Loc,
'10080' Dur,
L_Week_Start_Date StartDate,
(CASE
WHEN SkuXFcst.StartDate BETWEEN L_Week_Start_Date
AND L_Week_Start_Date + 6
THEN SUM(SkuXFcst.Qty) OVER(PARTITION BY SkuXFcst.Item, SkuXFcst.Loc)
ELSE 0
END) P1,
(CASE
WHEN SkuXFcst.StartDate BETWEEN L_Week_Start_Date + 7
AND L_Week_Start_Date + 13
THEN SUM(SkuXFcst.Qty) OVER(PARTITION BY SkuXFcst.Item, SkuXFcst.Loc)
ELSE 0
END) P8,
(CASE
WHEN SkuXFcst.StartDate BETWEEN L_Week_Start_Date + 14
AND L_Week_Start_Date + 20
THEN SUM(SkuXFcst.Qty) OVER(PARTITION BY SkuXFcst.Item, SkuXFcst.Loc)
ELSE 0
END) P15,
(CASE
WHEN SkuXFcst.StartDate BETWEEN L_Week_Start_Date + 21
AND L_Week_Start_Date + 27
THEN SUM(SkuXFcst.Qty) OVER(PARTITION BY SkuXFcst.Item, SkuXFcst.Loc)
ELSE 0
END) P22
FROM SCPOMGR.SkuExternalFcst SkuXFcst,
SCPOMGR.Sku Sku
WHERE SkuXFcst.Item = Sku.Item
AND SkuXFcst.Loc = Sku.Loc
AND ((SkuXFcst.StartDate BETWEEN Sku.U_Range_Start AND Sku.U_Range_End)
OR Sku.U_Range_Start = TO_DATE('01/01/1970', 'DD/MM/YYYY')))
GROUP BY Item,
Loc,
Dur,
StartDate
答案 0 :(得分:0)
create table SkuXFcst as
SELECT 21257 as item, 903 as loc, TO_DATE('2018-12-11')as startdate, 14400 as dur , 100 as qty from dual union all
SELECT 21257, 664, TO_DATE('2018-12-10'), 14400, 100 from dual union all
SELECT 11064, 101, TO_DATE('2018-11-26'), 43200, 300 from dual union all
SELECT 21257, 315, TO_DATE('2018-12-01'), 14400, 100 from dual union all
SELECT 21257, 314, TO_DATE('2018-12-10'), 14400, 100 from dual union all
SELECT 21257, 903, TO_DATE('2018-12-10'), 14400, 1000 from dual union all
SELECT 19510, 502, TO_DATE('2018-12-20'), 14400, 50 from dual union all
SELECT 19510, 502, TO_DATE('2018-12-20'), 14400, 500 from dual union all
SELECT 19507, 615, TO_DATE('2018-12-20'), 14400, 50 from dual union all
SELECT 19507, 615, TO_DATE('2018-12-22'), 14400, 50 from dual union all
SELECT 19510, 502, TO_DATE('2018-12-01'), 0 , 0 from dual ;
SELECT item,
loc,
dur,
SUM(CASE
WHEN SkuXFcst.StartDate BETWEEN to_date('2018-12-02','YYYY-MM-DD')
AND to_date('2018-12-02','YYYY-MM-DD')+ 6 THEN SkuXFcst.Qty
ELSE 0
END) AS P1,
SUM(CASE
WHEN SkuXFcst.StartDate BETWEEN to_date('2018-12-02','YYYY-MM-DD') + 7
AND to_date('2018-12-02','YYYY-MM-DD') + 13 THEN SkuXFcst.Qty
ELSE 0
END) P8,
SUM(CASE
WHEN SkuXFcst.StartDate BETWEEN to_date('2018-12-02','YYYY-MM-DD') + 14
AND to_date('2018-12-02','YYYY-MM-DD') + 20 THEN SkuXFcst.Qty
ELSE 0
END) P15,
SUM(CASE
WHEN SkuXFcst.StartDate BETWEEN to_date('2018-12-02','YYYY-MM-DD') + 21
AND to_date('2018-12-02','YYYY-MM-DD') + 27 THEN SkuXFcst.Qty
ELSE 0
END) P22
from SkuXFcst
GROUP BY item,
loc,
dur