1.2

 avatar
unknown
sqlserver
2 years ago
1.4 kB
3
Indexable
SELECT
    ftxn.[BrandID],
	ftxn.[BrandName],
	ftxn.[Customer_Segment],
	SUM(ftxn.[QTY]) AS [VOL],
	SUM(ftxn.[AMT]) AS [AMT]
FROM
	(
	SELECT 
		txn.[CustomerID],
		txn.[BUID],
		txn.[BranchID],
		txn.[SKUCode],
		txn.[QTY],
		cus.[Member_Number],
		cus.[Request_No],
		cus.[Customer_Segment],
		pm.[SubDeptID],
		pm.[BrandID],
		pm.[SKU_Price],
		txn.[QTY] * pm.[SKU_Price] AS [AMT]

	-- TXN TABLE 
	FROM    
		(SELECT [CustomerID],[BUID],[BranchID],[SKUCode],[QTY] FROM [Sales_SKU_CDS]
		UNION
		SELECT [CustomerID],[BUID],[BranchID],[SKUCode],[QTY] FROM [Sales_SKU_CDS]) txn

	-- USE [CUST_ID] get [Customer_Segment]
	LEFT JOIN
		(SELECT
			sbl.[CustomerID],
			sbl.[Member_Number],
			crm.[Request_No],
			csts.[Customer_Segment]
		FROM [Customer_SBL] sbl
		LEFT JOIN [CustomerRequest_CRM] crm
		ON sbl.[Member_Number] = crm.[Member_Number]
		LEFT JOIN [Customer_Status] csts
		ON sbl.[Member_Number] = csts.[Customer_Segment]) cus
	ON txn.[CustomerID] = cus.[CustomerID]

	-- USE [SKUCode] get [SubDeptID],[BrandID],[BrandName],[SKU_Price]
	LEFT JOIN [Product_Master] pm
	ON txn.[SKUCode] = pm.[SKUCode]

	-- FILTER
	WHERE cus.[Request_No] IN ('AA1234','BB4421')
	AND pm.[SubDeptID] = 101
	) ftxn
GROUP BY 
    ftxn.[BrandID],
	ftxn.[BrandName],
	ftxn.[Customer_Segment]
ORDER BY -- FOR SORTED VIEW
    ftxn.[BrandID],
	ftxn.[BrandName],
	ftxn.[Customer_Segment]