You can unpivot and re-aggregate. Here is one method:
select id, sku,
max(case when seqnum = 1 then mg end) as mg1,
max(case when seqnum = 2 then mg end) as mg1,
. . .
max(case when seqnum = 9 then mg end) as mg9
from (select i.*, row_number() over (order by mg desc) as seqnum
from (select id, sku, mg1 as mg from t union all
select id, sku, mg2 as mg from t union all
. . .
select id, sku, mg9 as mg from t
) i
where mg is not null
) i;
If you are using SQL Server -- or another database that supports lateral joins -- then the best method is:
select t.id, t.sku, v.*
from t cross apply
(select max(case when seqnum = 1 then mg end) as mg1,
max(case when seqnum = 2 then mg end) as mg2,
. . .
max(case when seqnum = 9 then mg end) as mg9
from (select mg, row_number() over (order by mg desc) as seqnum
from (values (t.mg1), (t.mg2), . . ., (t.mg9)
) v(mg)
where mg is not null
) v
) v;
There is a big performance advantage in doing the group by
in the subquery versus in the outer query.
with ordered as (
select ID, SKU,
mg, row_number() over (partition by ID order by mg desc) as rn
from T cross apply (
select * from (values (mg1), (mg2)) as dummy(mg)) as up
)
select ID, SKU,
min(case when rn = 1 then mg end) as mg1,
min(case when rn = 2 then mg end) as mg2
from ordered
group by ID, SKU
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.