SQL如何按顺序重新排列列(从大到小)

时间:2020-01-16 02:46:19

标签: sql sql-server

我有一个[产品]表,用于产品和利润。我需要确保MG1> MG2> MG3> ...> MG9 如何以更简便的方式重新排列此列? enter image description here

尝试使用If else和case并以很长的代码结束。 非常感谢。

2 个答案:

答案 0 :(得分:0)

您可以取消透视和重新聚合。这是一种方法:

 { 
    path: '/dashboard', 
    name: 'dashboard', 
    component: () => import('@/views/Dashboard'),
    meta: { requiresAuth: true },
 },
 { 
    path: '/login', 
    name: 'login', 
    component: () => import('@/views/auth/Login'),
    meta: { requiresVisitor: true }
  },

如果您使用的是SQL Server或其他支持横向联接的数据库,那么最好的方法是:

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;

在子查询中执行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; 与在外部查询中进行group by相比,具有很大的性能优势。

答案 1 :(得分:0)

Window