Saturday, June 28, 2014

Display total qty sold of each item of each store

Here's an example of how to do what you want without pivots. The performance might not be as good, but it should work for you. I've also included some example data and basic DDL *long accusing glare*.



DECLARE @items table (ID int, description varchar(30))
INSERT INTO @items
( ID, description )
VALUES
( 0,'Light Saber'),( 1,'Jedi Robe'),( 2,'Blaster'),
( 3,'Pod'),( 4,'T16'),( 5,'Womp Rat')

DECLARE @itemsSold TABLE (itemID INT, storeID INT, itemQuantity INT)
INSERT INTO @itemsSold
( itemID, storeID, itemQuantity )
VALUES
( 0, 0, 5),( 0, 1, 10),( 0, 2, 0),( 1, 0, 10),( 1, 1, 0),( 1, 2, 15),( 2, 0, 9),( 2, 1, 7),( 2, 2, 0),
( 3, 0, 0),( 3, 1, 0),( 3, 2, 1),( 4, 0, 3),( 4, 1, 1),( 4, 2, 2),( 5, 0, 54),( 5, 1, 32),( 5, 2, 128)

SELECT COALESCE(x.description,'Total') AS Item, SUM(x.allStores) AS AllStores, SUM(a.aStore) AS StoreA, SUM(b.bStore) AS StoreB, SUM(c.cstore) AS StoreC
FROM (
SELECT i.description, iso.itemID, SUM(iso.itemQuantity) AS allStores
FROM @items i
INNER JOIN @itemsSold iso
ON i.ID = iso.itemID
GROUP BY i.description, iso.itemID
) x
LEFT OUTER JOIN (
SELECT i.description, iso.itemID, iso.storeID, SUM(iso.itemQuantity) AS aStore
FROM @items i
INNER JOIN @itemsSold iso
ON i.ID = iso.itemID
GROUP BY i.description, iso.itemID, iso.storeID
) a
ON x.itemID = a.itemID
AND a.storeID = 0
LEFT OUTER JOIN (
SELECT i.description, iso.itemID, iso.storeID, SUM(iso.itemQuantity) AS bStore
FROM @items i
INNER JOIN @itemsSold iso
ON i.ID = iso.itemID
GROUP BY i.description, iso.itemID, iso.storeID
) b
ON x.itemID = b.itemID
AND b.storeID = 1
LEFT OUTER JOIN (
SELECT i.description, iso.itemID, iso.storeID, SUM(iso.itemQuantity) AS cStore
FROM @items i
INNER JOIN @itemsSold iso
ON i.ID = iso.itemID
GROUP BY i.description, iso.itemID, iso.storeID
) c
ON x.itemID = c.itemID
AND c.storeID = 2
GROUP BY x.description WITH ROLLUP


No comments:

Post a Comment