表如下
同学  语文 数学 英语
A       1    1   0
B       0    1   0
C       1    1   11表示及格,0表示不及格 
要查出某个同学哪门课及格了,语句怎么写?要求查出如下格式
A 语文,数学
B 数学
C 语文,数学,英语

解决方案 »

  1.   


    ;with cte(同学,语文,数学,英语) as
    (
    select 'A',1,1,0
    union all select 'B',0,1,0
    union all select 'C',1,1,1
    )
    select 同学, 及格科目=STUFF(及格科目,1,1,'')
    from
    (
    select 同学, 及格科目=(case when 语文=1 then N',语文' else '' end+
    case when 数学=1 then N',数学' else '' end+
    case when 英语=1 then N',英语' else '' end)
    from cte
    )t/*
    同学 及格科目
    A 语文,数学
    B 数学
    C 语文,数学,英语
    */
      

  2.   


    create table hx
    (同学 varchar(5),语文 int,数学 int,英语 int)insert into hx
     select 'A',1,1,0 union all
     select 'B',0,1,0 union all
     select 'C',1,1,1
    declare @tsql varchar(6000)select @tsql=isnull(@tsql+',','')+'['+b.name+']'
     from sys.tables a
     inner join sys.columns b on a.object_id=b.object_id
     where a.name='hx' and b.name<>'同学'select @tsql='with t as
    (select 同学,sub
     from hx a
     unpivot(val for sub in('+@tsql+')) u
     where val=1)
    select a.同学,
           stuff((select '',''+b.sub from t b 
                  where b.同学=a.同学 for xml path('''')),1,1,'''') ''及格科目''
     from t a group by a.同学'
     
    exec(@tsql)/*
    同学    及格科目
    ----- -----------------
    A     语文,数学
    B     数学
    C     语文,数学,英语(3 row(s) affected)
    */
      

  3.   


    ;with cte(同学,语文,数学,英语) as
    (
    select 'A',1,1,0
    union all select 'B',0,1,0
    union all select 'C',1,1,1
    )select 同学, 及格科目=STUFF(及格科目,1,1,'')
    from
    (
    select 同学, 
           replace(replace(cast(语文 as varchar),'1',',语文'),'0','') + 
           replace(replace(cast(数学 as varchar),'1',',数学'),'0','') +
           replace(replace(cast(英语 as varchar),'1',',英语'),'0','') as 及格科目
    from cte
    )t
    /*
    同学 及格科目
    A 语文,数学
    B 数学
    C 语文,数学,英语
    */
      

  4.   

    with tb(同学,  语文, 数学, 英语) as
    (
    select 'A',       1,    1,   0 union all
    select 'B',       0,    1,   0 union all
    select 'C',       1,    1,   1
    )
    select
     同学,
     case when 语文 = 1 then '语文' else '' end as 语文,
     case when 数学 = 1 then '数学' else '' end as 数学,
     case when 英语 = 1 then '英语' else '' end as 英语
    from tb