Or this variant-- Prepare test datadeclare @table table (seq tinyint, area smallint, page tinyint)insert @tableselect 1, 300, 0 union allselect 1, 200, 0 union allselect 1, 100, 0 union allselect 1, 400, 0 union allselect 2, 600, 0 union allselect 2, 500, 0 union allselect 2, 300, 0 union allselect 2, 700, 0-- Do the work (this is the code you run on your computer).select t0.seq, b0.i * isnull(max(t0.area), 0) + b1.i * isnull(max(t1.area), 0) + b2.i * isnull(max(t2.area), 0) areafrom ( select seq, max(area) area from @table group by seq ) t0left join @table t1 on t1.seq = t0.seq and t1.area < t0.arealeft join @table t2 on t2.seq = t1.seq and t2.area < t1.areacross join (select 0 i union all select 1) b0cross join (select 0 i union all select 1) b1cross join (select 0 i union all select 1) b2where b0.i + b1.i + b2.i = 1group by t0.seq, b0.i, b1.i, b2.ihaving b0.i * isnull(max(t0.area), 0) + b1.i * isnull(max(t1.area), 0) + b2.i * isnull(max(t2.area), 0) > 0order by t0.seq, b0.i * isnull(max(t0.area), 0) + b1.i * isnull(max(t1.area), 0) + b2.i * isnull(max(t2.area), 0) DESC
This is the outputSeq Area--- ---- 1 400 1 300 1 200 2 700 2 600 2 500
Peter LarssonHelsingborg, Sweden