有表table1:bh xm sl
1 张三 12
2 李四 14
3 李四 29
4 王五 11
5 赵波 12
6 李四 6
7 李俊 7
8 赵波 9
9 李四 30
10 赵波 10想统计xm为李四和不是李四的总slselect xm,case when xm= '李四' then sum(sl) else sum(sl) end 
from table1 group by xm我这样写不对?该怎么写

解决方案 »

  1.   

    select xm , sum(sl) from table1 where xm = '李四'
    union 
    select xm = '不是李四', sum(sl) from table1 where xm <> '李四'
      

  2.   

    create table table1(bh int,xm varchar(10),sl int)
    insert into table1 values(1 , '张三', 12)
    insert into table1 values(2 , '李四', 14)
    insert into table1 values(3 , '李四', 29)
    insert into table1 values(4 , '王五', 11)
    insert into table1 values(5 , '赵波', 12)
    insert into table1 values(6 , '李四', 6)
    insert into table1 values(7 , '李俊', 7)
    insert into table1 values(8 , '赵波', 9)
    insert into table1 values(9 , '李四', 30)
    insert into table1 values(10, '赵波', 10)
    goselect xm , sum(sl) from table1 where xm = '李四' group by xm
    union 
    select xm = '不是李四', sum(sl) from table1 where xm <> '李四'drop table table1/*
    xm                     
    ---------- ----------- 
    不是李四       61
    李四         79(所影响的行数为 2 行)
    */
      

  3.   

    create table table1(bh int,xm varchar(10),sl int)
    insert into table1 values(1 , '张三', 12)
    insert into table1 values(2 , '李四', 14)
    insert into table1 values(3 , '李四', 29)
    insert into table1 values(4 , '王五', 11)
    insert into table1 values(5 , '赵波', 12)
    insert into table1 values(6 , '李四', 6)
    insert into table1 values(7 , '李俊', 7)
    insert into table1 values(8 , '赵波', 9)
    insert into table1 values(9 , '李四', 30)
    insert into table1 values(10, '赵波', 10)
    go--1
    select xm , sum(sl) sl from table1 where xm = '李四' group by xm
    union 
    select xm = '不是李四', sum(sl) sl from table1 where xm <> '李四'--2
    select case when xm = '李四' then '李四' else '不是李四' end xm, sum(sl) sl from table1 group by case when xm = '李四' then '李四' else '不是李四' end
    drop table table1/*
    xm       sl          
    -------- ----------- 
    不是李四     61
    李四       79(所影响的行数为 2 行)
    */