简体   繁体   中英

SQL how to rearrange column in order (From big to small value)

I have a table [PRODUCT] for product and margin. I need to make sure MG1>MG2>MG3>...>MG9 How do I rearrange this column in easier manner? 在此处输入图片说明

Tried using If else and case and end up with a very long code. Thank you very much.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM