You don't need to change the localnotenumber to get your desired results. We can just use a derived table to get the data elements without localnotenumber, then join back to the main table and grab the minimum localnotenumber.select t2.reference, min(t1.localnotenumber), t2.quantity, t2.pricefrom table1 t1inner join( select reference, sum(quantity) as quantity, sum(price) as price from table1 group by reference) t2on t1.reference = t2.referencegroup by t2.reference, t2.quantity, t2.quantity, t2.price
Here's my test case:create table table1 (id tinyint, reference char(7), localnotenumber char(13), quantity tinyint, price decimal(3,2))insert into table1 values(1, 'CD10001', 'd091207-10001', 2, 3.99)insert into table1 values(2, 'CD10001', 'd091207-10002', 1, 4.99)insert into table1 values(3, 'CD10002', 'd091207-10003', 2, 5.99)insert into table1 values(4, 'CD10002', 'd091207-10004', 1, 6.99)insert into table1 values(5, 'CD10002', 'd091207-10005', 2, 7.99)insert into table1 values(6, 'CD10003', 'd091207-10006', 1, 8.99)select t2.reference, min(t1.localnotenumber), t2.quantity, t2.pricefrom table1 t1inner join( select reference, sum(quantity) as quantity, sum(price) as price from table1 group by reference) t2on t1.reference = t2.referencegroup by t2.reference, t2.quantity, t2.quantity, t2.pricedrop table table1
Tara KizerMicrosoft MVP for Windows Server System - SQL Serverhttp://weblogs.sqlteam.com/tarad/