Skip to content
Advertisement

SQL – combine rows conditionally on the value of previous row

My issue I believe is best explained by using an example:

Sample Data

SO Customer Product Description Quantity Extension Country
01 xxx 123 Product A 01 20.00 USA
02 yyy 456 Product B 02 25.00 China
02 yyy 456 Product B 01 12.50 China
02 yyy 789 Product C 01 50.00 Mexico
03 zzz 789 Product C 01 50.00 Mexico
03 zzz 789 Product C 01 50.00 Mexico

Desired output:

SO Customer Product Description Quantity Extension Country
01 xxx 123 Product A 01 20.00 USA
02 yyy 456 Product B 03 37.50 China
02 yyy 789 Product C 01 50.00 Mexico
03 zzz 789 Product C 02 100.00 Mexico

So the key issue I’m having is grouping by the SO, then if there are duplicate lines of Product, consolidating lines into one. In the real data, there could be many lines to summarize or none at all – it could all be unique.

Advertisement

Answer

This looks like group by:

select SO, Customer, Product, Description, sum(Quantity), sum(Extension),   Country
from t
group by SO, Customer, Product, Description, Country;

Note that quantity looks strange. Numbers in SQL are not shown with leading zeros — and numbers should be stored as numbers, not strings.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement