June 16, 2010 at 9:01 am
Hello,
I have a table with following data:
code
Code Quantity
-------- -----------
ProductA 5
ProductA 5
ProductA 5
ProductB 5
ProductB 5
ProductA 5
ProductA 5
I'd like to group and sum data to get following result:
code
Code Quantity
-------- -----------
ProductA 15
ProductB 10
ProductA 10
How to do it without cursor? Can anybody help me, please?
SQL for data preparation:
SELECT * into #tmp_table from
(
SELECT 'ProductA' AS Code, 5 AS Quantity
UNION ALL
SELECT 'ProductA' AS Code, 5 AS Quantity
UNION ALL
SELECT 'ProductA' AS Code, 5 AS Quantity
UNION ALL
SELECT 'ProductB' AS Code, 5 AS Quantity
UNION ALL
SELECT 'ProductB' AS Code, 5 AS Quantity
UNION ALL
SELECT 'ProductA' AS Code, 5 AS Quantity
UNION ALL
SELECT 'ProductA' AS Code, 5 AS Quantity
) as tmp
SELECT * FROM #tmp_table
drop table #tmp_table
June 16, 2010 at 10:20 am
This should help:
SELECT * into #tmp_table from
(
SELECT 1 AS ID, 'ProductA' AS Code, 5 AS Quantity
UNION ALL
SELECT 2 AS ID, 'ProductA' AS Code, 5 AS Quantity
UNION ALL
SELECT 3 AS ID, 'ProductA' AS Code, 5 AS Quantity
UNION ALL
SELECT 4 AS ID, 'ProductB' AS Code, 5 AS Quantity
UNION ALL
SELECT 5 AS ID, 'ProductB' AS Code, 5 AS Quantity
UNION ALL
SELECT 6 AS ID, 'ProductA' AS Code, 5 AS Quantity
UNION ALL
SELECT 7 AS ID, 'ProductA' AS Code, 5 AS Quantity
) as tmp
;WITH TmpCTE AS (
SELECT Id, Code, Quantity,
ROW_ID = ROW_NUMBER() OVER (ORDER BY ID),
ROW_ID_GRP = ROW_NUMBER() OVER(PARTITION BY Code ORDER BY ID)
FROM #tmp_table
),
RankedCTE AS (
SELECT *, GROUP_ID = ROW_ID - ROW_ID_GRP
FROM TmpCTE
)
SELECT Code, SUM(Quantity)
FROM RankedCTE
GROUP BY GROUP_ID, Code
ORDER BY MIN(ID)
drop table #tmp_table
-- Gianluca Sartori
June 17, 2010 at 2:33 am
Hi Gianluca,
this seems to be the solution.
Thanks a lot. You are great!
June 17, 2010 at 2:37 am
You're welcome.
Glad I could help.
-- Gianluca Sartori
Viewing 4 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply