有一张表如下
name     m1      m2      m3      m4
张三 NULL 2000 1500 2500
赵四 2000 NULL 3000 2000
王五 2500 2000 NULL 35001.如何求每个人的平均值,和总和.
2.如何求每个人不为null的平均值,和总和.

解决方案 »

  1.   

    1.如何求每个人的平均值,和总和.
    ---------------------
    sum(col)/count(*)2.如何求每个人不为null的平均值,和总和. 
    ----------------
    avg(col)
      

  2.   

    --1.如何求每个人的平均值,和总和. select name , 
           (inull(m1,0) + inull(m2,0) + inull(m3,0) + inull(m4,0))*1.0/4 平均值,
           inull(m1,0) + inull(m2,0) + inull(m3,0) + inull(m4,0) 总和
    from tb--2
    2.如何求每个人不为null的平均值,和总和. select name , 
           (inull(m1,0) + inull(m2,0) + inull(m3,0) + inull(m4,0))*1.0/(case when m1 is not null then 1 else 0 end + case when m2 is not null then 1 else 0 end + case when m3 is not null then 1 else 0 end + case when m4 is not null then 1 else 0 end) 平均值,
           inull(m1,0) + inull(m2,0) + inull(m3,0) + inull(m4,0) 总和
    from tb
      

  3.   

    --1.如何求每个人的平均值,和总和. select name , 
           (isnull(m1,0) + isnull(m2,0) + isnull(m3,0) + isnull(m4,0))*1.0/4 平均值,
           isnull(m1,0) + isnull(m2,0) + isnull(m3,0) + isnull(m4,0) 总和
    from tb--2
    2.如何求每个人不为null的平均值,和总和. select name , 
           (isnull(m1,0) + isnull(m2,0) + isnull(m3,0) + isnull(m4,0))*1.0/(case when m1 is not null then 1 else 0 end + case when m2 is not null then 1 else 0 end + case when m3 is not null then 1 else 0 end + case when m4 is not null then 1 else 0 end) 平均值,
           isnull(m1,0) + isnull(m2,0) + isnull(m3,0) + isnull(m4,0) 总和
    from tb
      

  4.   

    declare @tmp table(name varchar(100),m1 int,m2 int,m3 int,m4 int)
    insert into @tmp
    select 
    name,
    m1=case m1 when null then 0 else m1 end,
    m2=case m2 when null then 0 else m2 end,
    m3=case m3 when null then 0 else m3 end,
    m4=case m4 when null then 0 else m4 end
    from 你的表
    --1.如何求每个人的平均值,和总和. select 平均值=(m1+m2+m3+m4)/4,总和=m1+m2+m3+m4 from @tmp
      

  5.   

    按照大师的写法写下动态SQL语句,这样不管mX中X有多少都能实现declare @sql varchar(8000)
    set @sql = 'select name,('
    select @sql=@sql++'isnull('+ name+',0)+'
    from syscolumns where name! = 'name' and ID = object_id('统计信息')
    set @sql = left(@sql,len(@sql)-1)+')*1.0/('
    select @sql=@sql+'case when '+ name+' is not null then 1 else 0 end +'
    from syscolumns where name! = 'name' and ID = object_id('统计信息')
    set @sql=left(@sql,len(@sql)-1)+') 平均值,('
    select @sql=@sql++'isnull('+ name+',0)+'
    from syscolumns where name! = 'name' and ID = object_id('统计信息')
    set @sql = left(@sql,len(@sql)-1)+') 总和 from 统计信息'
    print @sql 
    exec(@sql)
      

  6.   

    1.如何求每个人的平均值,和总和. 
    2.如何求每个人不为null的平均值,和总和. 
    ------------
    NULL的不就转成0了吗  所以这两题目是一样的