班次表:班次号 班名-1 无 
1 早班 
2 中班 
3 夜班 
月考勤报表:姓名 1号 2号 3号 4号 .... 31号张三 -1 -1 -1 -1 -1 -1
李四 -1 -1 -1 -1 -1 -1
王五 -1 -1 -1 -1 -1 -1
张六 -1 -1 -1 -1 -1 -1  
王勤 -1 -1 -1 -1 -1 -1
小刘 -1 -1 -1 -1 -1 -1 月考勤表记录的1号,2号,3号,4号是日期,对应的数据是班次,请问怎么才能将-1显示为无 ,2显示中班,等等。
数据库是MS-sql2000 ,我知道代码可以实现但是比较复杂,SQL可不可以一句话出来

解决方案 »

  1.   


    --用CASE WHEN THEN
    select case colname when -1 then '无' when 1 then '早班' when 2 then '中班' else 夜班 end
      

  2.   

    ---测试数据---
    if object_id('[班次表]') is not null drop table [班次表]
    go
    create table [班次表]([班次号] int,[班名] varchar(4))
    insert [班次表]
    select -1,'无' union all
    select 1,'早班' union all
    select 2,'中班' union all
    select 3,'夜班'
    if object_id('[月考勤报表]') is not null drop table [月考勤报表]
    go
    create table [月考勤报表]([姓名] varchar(4),[1号] int,[2号] int,[3号] int,[4号] int,[....] int,[31号] int)
    insert [月考勤报表]
    select '张三',-1,-1,-1,-1,-1,-1 union all
    select '李四',-1,-1,-1,-1,-1,-1 union all
    select '王五',-1,-1,-1,-1,-1,-1 union all
    select '张六',-1,-1,-1,-1,-1,-1 union all
    select '王勤',-1,-1,-1,-1,-1,-1 union all
    select '小刘',-1,-1,-1,-1,-1,-1
     
    ---查询---
    select 
      a.姓名,
      [1号]=max(case a.[1号] when b.[班次号] then b.[班名] end),   
      [2号]=max(case a.[2号] when b.[班次号] then b.[班名] end),
      [3号]=max(case a.[3号] when b.[班次号] then b.[班名] end),
      [4号]=max(case a.[4号] when b.[班次号] then b.[班名] end),
      [....]=max(case a.[....] when b.[班次号] then b.[班名] end),
      [31号]=max(case a.[31号] when b.[班次号] then b.[班名] end)
    from 
      [月考勤报表] a 
    left join 
      班次表 b 
    on 1=1 
    group by a.姓名---结果---
    姓名   1号   2号   3号   4号   .... 31号  
    ---- ---- ---- ---- ---- ---- ---- 
    李四   无    无    无    无    无    无
    王勤   无    无    无    无    无    无
    王五   无    无    无    无    无    无
    小刘   无    无    无    无    无    无
    张六   无    无    无    无    无    无
    张三   无    无    无    无    无    无(所影响的行数为 6 行)