--一条SQL写不出来,只能用动态的
declare @s varchar(8000)
set @s=''
select @s=@s+' when '''+A+''' then(select max(A) from ['+A+'])'
from [table] group by A
exec('select B,C=case A'+@s+' end from [table]')
go

解决方案 »

  1.   

    --示例--示例数据
    create table [table](A sysname,B varchar(10))
    insert [table] select 'table_1','a'
    union  all     select 'table_2','b'create table table_1(A int)
    insert table_1 select 1
    union  all     select 2create table table_2(A int)
    insert table_2 select 3
    union  all     select 4
    go--一条SQL写不出来,只能用动态的
    declare @s varchar(8000)
    set @s=''
    select @s=@s+' when '''+A+''' then(select max(A) from ['+A+'])'
    from [table] group by A
    exec('select B,C=case A'+@s+' end from [table]')
    go--删除测试
    drop table [table],table_1,table_2/*--测试结果B          C           
    ---------- ----------- 
    a          2
    b          4
    --*/
      

  2.   

    --如果楼主一定要追求一句的话,这就是一句了exec('set nocount on declare @s varchar(8000) set @s='''' select @s=@s+'' when ''''''+A+'''''' then(select max(A) from [''+A+''])'' from [table] group by A exec(''select B,C=case A''+@s+'' end from [table]'')')
      

  3.   

    一句话搞不定,类似:
    declare @ss varchar(8000)
    set @ss = ''
    select @ss = 'select ' + b + ',(select max(a) from ' + a + ') union all ' from [table]
    set @ss = right(@ss,len(@ss) - 11)
    --注意是否可能超过8000字符
    exec(@ss)
      

  4.   

    开了个会,没想到一提交第一句话和zjcxc(邹建) 几乎相同。
    ^_^!
      

  5.   

    谢谢大家的帮忙,尤其能得到zjcxc(邹建)大哥的回复感到很荣幸!我去试一试。