表:教师 星期张三 一李四 二张三 三王五 一张三 四李四 三王五 二李四 四王五 三 怎么把上面表用sql得到下面结果?教师     星期一   星期二   星期三    星期四张三 有 有 有李四 有 有 有王五 有 有 有

解决方案 »

  1.   

    select 
    教师,
    星期一=MAX(case when 星期='-' then '有' else '' end),
    星期二=MAX(case when 星期='二' then '有' else '' end),
    星期三=MAX(case when 星期='三' then '有' else '' end),
    星期四=MAX(case when 星期='四' then '有' else '' end)
    from tb 
    group by 教师
      

  2.   

    select 教师,
    星期一=case 星期 when '星期一' then '有' else '无' end,
    星期二=case 星期 when '星期二' then '有' else '无' end,
    星期三=case 星期 when '星期三' then '有' else '无' end,
    星期四=case 星期 when '星期四' then '有' else '无' end,
    星期五=case 星期 when '星期五' then '有' else '无' end,
    星期六=case 星期 when '星期六' then '有' else '无' end,
    星期日=case 星期 when '星期日' then '有' else '无' end
    from tb
    group by 教师
      

  3.   

    select 教师,
    星期一=case 星期 when '星期一' then '有' else '' end,
    星期二=case 星期 when '星期二' then '有' else '' end,
    星期三=case 星期 when '星期三' then '有' else '' end,
    星期四=case 星期 when '星期四' then '有' else '' end,
    星期五=case 星期 when '星期五' then '有' else '' end,
    星期六=case 星期 when '星期六' then '有' else '' end,
    星期日=case 星期 when '星期日' then '有' else '' end
    from tb
    group by 教师
      

  4.   

    犯个常识性错误,奶奶的IF OBJECT_ID('tb') IS NOT NULL
    DROP TABLE tb
    GO
    create table tb(教师 varchar(10), 星期 varchar(2))
    insert tb SELECT '张三','一'union all select '李四','二' union all select '张三','三' union all select '王五','一' union all select '张三','四' union all select '李四','三' union all select '王五','二' union all select '李四','四' union all select '王五','三' 
    select 教师,
    星期一=max(case 星期 when '一' then '有' else '' end),
    星期二=max(case 星期 when '二' then '有' else '' end),
    星期三=max(case 星期 when '三' then '有' else '' end),
    星期四=max(case 星期 when '四' then '有' else '' end)from tb
    group by 教师
    /*
    教师         星期一  星期二  星期三  星期四
    ---------- ---- ---- ---- ----
    李四              有    有    有
    王五         有    有    有    
    张三         有         有    有(3 行受影响)
    */