在SQL Server中按其他值排序

时间:2013-07-20 04:51:37

标签: sql sql-server

我的Select Command的结果集是:

1 Null Null Null
1 1    Null Null
1 1    Null 1
1 1    1    Null

但我需要像这样重新排序:

1 Null Null Null
1 1    Null Null
1 1    1    Null
1 1    Null 1

我该怎么做?

SELECT语句:

 select K,
        Null As M,
        Null As T1,
        Null As T2,
        SUM(debit) SumDebit 
   from h 
        join i On h.HdrId = i.HdrIdRef 
        Group by K 

           Union 

 select K,
        M,
        Null As T1,
        Null As T2,
        SUM(debit) SumDebit 
    from h 
         join i On h.HdrId = i.HdrIdRef 
         Group by K,M 

             Union 
 Select * 
   From
       ( select K,
                M,
                T1,
                Null As T2,
                SUM(debit) SumDebit 
           from h 
                join i On h.HdrId = i.HdrIdRef 
                Group by K,M,T1
      ) A 
  Where A.T1 Is Not Null 

              Union 

 Select * 
  From
     ( select K,
              M,
              T1,
              T2,
              SUM(debit) SumDebit 
          from h 
               join i On h.HdrId = i.HdrIdRef 
               Group by K,M,T1,T2
     ) A 
 Where A.T2 Is Not Null 
       Order By K, M, T1, T2 

1 个答案:

答案 0 :(得分:1)

SELECT *
FROM table
ORDER BY ISNULL(Col4, 0), ISNULL(Col3, 0), ISNULL(Col2, 0), ISNULL(Col1, 0)

我假设您希望排序从最右侧的列开始,基于您的输出