Essentially I need to group unique product data into a single row when:
- The supplier sku matches
- The price for the products match (or) 1 of the product lines is equal to ‘0.00’
Here is a sample dataset set along with a working query for what I’m trying to accomplish. I’m simply not entirely comfortable that this is the best way to perform this query.
DECLARE @Test TABLE
(
SupplierSKU VARCHAR(25),
Description VARCHAR(50),
Quantity VARCHAR(25),
Price VARCHAR(25)
)
INSERT INTO @Test
SELECT '123', 'APPLES', '15', '0.00'
INSERT INTO @Test
SELECT '124', 'ORANGES', '10', '15.34'
INSERT INTO @Test
SELECT '123', 'APPLES', '5', '27.40'
INSERT INTO @Test
SELECT '125', 'PLUMS', '67', '34.86'
INSERT INTO @Test
SELECT '124', 'ORANGES', '10', '15.78'
INSERT INTO @Test
SELECT '125', 'PLUMS', '3', '34.86'
SELECT SupplierSKU, Description, SUM(Quantity) AS [Quantity], MAX(Price) AS [Price]
FROM
(
SELECT SupplierSKU, Description, SUM(CAST(Quantity AS INT)) AS [Quantity], (SELECT MAX(CAST(Price AS MONEY)) AS [Price] FROM @Test ti WHERE ti.SupplierSKU = t.SupplierSKU AND ti.Price = t.price AND ti.Price <> '0.00') AS [Price]
FROM @Test t
GROUP BY SupplierSKU, Description, Price
) pdata
GROUP BY pdata.SupplierSKU, pdata.Description
The desired results:
SupplierSKU Description Quantity Price
123 APPLES 20 27.40
124 ORANGES 10 15.34
124 ORANGES 10 15.78
125 PLUMS 70 34.86
First I repaired your own solution
Then I rewrote your solution to something more readable
You may notice i get the right quantity of apples (15+5 = 20)