将嵌套的SQL语句聚合到更少的列

时间:2018-04-05 19:13:19

标签: sql oracle nested aggregate

我正在尝试汇总我的数据并将其与SKU以及与该SKU相关联的群集ID进行分组。

我当前的输出带回大约40,000行(5个SKU' s * 8,000个商店)但是我只需要35个。

我的代码:

SELECT DISTINCT E.*
FROM ALC_ITEM_SOURCE P
RIGHT JOIN
(
SELECT D.* ,SUM(L.ALLOCATED_QTY) AS TOTAL_ALLOCATED
FROM ALC_ITEM_LOC L
RIGHT JOIN 
(
SELECT C.*
FROM STORE S, 
(
SELECT A.*, B.LOCATION AS STORE_NUMBER
FROM FDT_MAP_CLUSTER_LOCATION B, 
(
SELECT DISTINCT SS.ALLOC_CLUSTER_ID, SS.ALLOC_CLUSTER_NAME, SS.SKU
from fdt_maptool_sas_data ss
WHERE SS.SKU IN (1099866,
1099896,
1000898,
1000960,
1000988 
)
AND SS.ORDER_NO IS NOT NULL
AND ALLOC_CLUSTER_NAME NOT LIKE '%DC Cluster%'
GROUP BY SS.ALLOC_CLUSTER_ID, SS.ALLOC_CLUSTER_NAME, SS.WORKSHEET_ID, SS.SKU
)A 
WHERE B.CLUSTER_ID = A.ALLOC_CLUSTER_ID
AND B.LOCATION_TYPE = 'S'
)C
WHERE S.STORE = C.STORE_NUMBER
AND S.STORE_CLOSE_DATE IS NULL
AND S.DISTRICT NOT IN (997, 998, 999)
AND S.STORE_OPEN_DATE <= SYSDATE
)D
ON L.ITEM_ID = D.SKU
AND L.LOCATION_ID = D.STORE_NUMBER

GROUP BY D.ALLOC_CLUSTER_ID, D.ALLOC_CLUSTER_NAME, D.SKU, D.STORE_NUMBER
)E
ON P.ITEM_ID = E.SKU
AND P.SOURCE_TYPE <> 4
AND P.RELEASE_DATE > '01-FEB-2018'

我想要的结果将包含:

SKU       Cluster_ID   Total_allocated  Count(stores) 
1000989    1AA STORES   258             200
1000989    2A STORES    78              600
1000989    B STORES     36              500
1000989    C STORES     114             100
1000989    D STORES     144             1222
1000989    E STORES     168             600
1000989    F STORES     60              501

这是每个群集ID每个商店分配的总和的总和。

正如你所看到的,每个SKU都有一个等级(AA-F),我想重复这5次,因为我有5个SKU。

基本上我问我如何将我的数据汇总到现在的40,000行中的上表。

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

只是为了使你的sql更好更整洁,你应该避免在&#39;其中&#39;声明。 另外我认为你与ALC_ITEM_SOURCE表无关,因为你几乎没有使用它。

您可以尝试使用此版本,或者至少开始使用它:

with mock.patch(...) as mock_func:
    some_function(1) # mock_func is called here

some_function(1) # the mock is no longer in place here