我有以下代码,大约需要10分钟才能运行。我想不通为什么......有什么建议吗?查找一个月销售额约51000行的交易。
WITH CUSTOMER_SALESTYPE AS (
SELECT CUSTOMER_ID
,CUSTOMER_NAME
,CASE Sales_type WHEN 'A' THEN 'TRADE'
WHEN 'B' THEN 'WHOLESALE'
WHEN 'C' THEN 'TRADE'
WHEN 'M' THEN 'WHOLESALE'
WHEN 'N' THEN 'WHOLESALE'
WHEN 'P' THEN 'TRADE'
WHEN 'S' THEN 'TRADE'
WHEN 'V' THEN 'WHOLESALE' END AS 'SALESTYPE'
,CASE B.STATE WHEN 'TAS' THEN 'VIC' ELSE B.STATE END AS 'STATE'
FROM BSIT_ERA_RAW_DATA.DBO.CUSTOMER A
LEFT JOIN BSIT_ERA_RAW_DATA.DBO.TERRITORY_REP B ON A.TERR_CODE = B.TERR_CODE
WHERE BSIT_STORE = 'STORE01'
AND B.STATE IN ('VIC','QLD','NSW','WA','SA','TAS')
)
SELECT B.STATE
,B.SALESTYPE
,C.BRAND_NAME
,SUM(TOTAL_SALE_AMT) AS 'Net Sales'
,SUM(TOTAL_COST) AS 'Net Cost'
,SUM(TOTAL_SALE_AMT) - SUM(TOTAL_COST) AS 'Net Margin'
,STR(100*((SUM(TOTAL_SALE_AMT) - SUM(TOTAL_COST)) / SUM(TOTAL_SALE_AMT)),5,2) + '%' AS 'Net Margin%'
FROM [BSIT_ERA_RAW_DATA].[dbo].[PROD_HIST] A
INNER JOIN CUSTOMER_SALESTYPE B ON A.CUST_NO = B.CUSTOMER_ID
INNER JOIN BSIT_ERA_RAW_DATA.dbo.DIM_PART C ON RIGHT(A.PART_NO,LEN(A.PART_NO)-2) = C.PART_NO
WHERE TRANS_DATE >= DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0)
AND TRANS_DATE < DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) , 0)
AND TRANS_TYPE IN ('SLS', 'CM')
AND INVOICE_NO IS NOT NULL
AND A.TRANS_CODE != 'L'
AND A.TRANS_CODE != 'PL'
OR
TRANS_DATE >= DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0)
AND TRANS_DATE < DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) , 0)
AND TRANS_TYPE IN ('SLS', 'CM')
AND INVOICE_NO IS NOT NULL
AND A.TRANS_CODE IS NULL
GROUP BY B.STATE
,B.SALESTYPE
,C.BRAND_NAME