有一个表:
ID     PWD
       odpwe
       akdso
       smpow
aa     bbbbb
mm     mksdi
cc     dsdsd
要的结果:
ID     PWD
aa     bbbbb
cc     dsdsd
mm     mksdi
       akdso
       smpow
       odpwe当ID 不为空时按ID 的升序排,当ID 为空时按PWD 的升序排。
另外。要求只用一个SQL语句。因为我用的是DataSource 
这是客户后来的要求。

解决方案 »

  1.   

    declare @t table(ID varchar(10),PWD varchar(10))
    insert into @t  select '','odpwe'
    union all select '','akdso'
    union all select '','smpow'
    union all select 'aa','bbbbb'
    union all select 'mm','mksdi'
    union all select 'cc','dsdsd'select * from @t order by case when ID<>'' then 0 else 1 end,PWD
      

  2.   

    declare @t table(ID varchar(10),pwd varchar(10))
    insert @t select null,'odpwe'
    union all select null,'akdso'
    union all select null,'smpow'
    union all select 'aa','bbbbb'
    union all select 'mm','mksdi'
    union all select 'cc','dsdsd'
    select * from @t
    order by case when id is null then 1 else 2 end desc
      

  3.   

    declare @t table(ID varchar(10),PWD varchar(10))
    insert into @t  select null,'odpwe'
    union all select null,'akdso'
    union all select null,'smpow'
    union all select 'aa','bbbbb'
    union all select 'mm','mksdi'
    union all select 'cc','dsdsd'select * from @t order by case when ID is not null then 0 else 1 end,PWD--如果是null值得话
      

  4.   

    declare @t table(ID varchar(10),PWD varchar(10))
    insert into @t select null,'odpwe'
    union all select null,'akdso'
    union all select null,'smpow'
    union all select 'aa','bbbbb'
    union all select 'mm','mksdi'
    union all select 'cc','dsdsd'select * from @t order by case when ID is not null then 0 else 1 end,PWD
    or select * from @t order by case when ID ='' then 0 else 1 end,PWD
      

  5.   

    我测试拉一下。
    最正确的应该是。
    declare @t table(ID varchar(10),PWD varchar(10))
    insert into @t select null,'odpwe'
    union all select null,'akdso'
    union all select null,'smpow'
    union all select 'zz','bbbbb'
    union all select 'mm','mksdi'
    union all select 'cc','dsdsd'
    select * from @t 
    select * from @t 
    order by case when ID is not null then id  else (select max(id)+'1' from @t)  end,PWD
      

  6.   

    declare @t table(ID varchar(10),PWD varchar(10))
    insert into @t select null,'odpwe'
    union all select null,'akdso'
    union all select null,'smpow'
    union all select 'zz','bbbbb'
    union all select 'mm','mksdi'
    union all select 'cc','dsdsd'select * from @t order by case when ID is not null then 0 else 1 end,ID,PWD