有表如下:
id    name   counts
1       a      34
2       b      56
3       c      24
4       d       2
5       e       1
6       f       3
由于d,e,f 的数据比较少,想把他们合在一起,得到以下数据表:
name    counts
a        34
b        56
c        24
other    6
应该怎样写这个语句?

解决方案 »

  1.   

    “由于d,e,f 的数据比较少”,這個少的判斷依據是什麼??少於10??
      

  2.   

    select case when name not in ('a','b','c') then 'others' else name end,sum(counts)
    from tablename
    group by case when name not in ('a','b','c') then 'others' else name end
      

  3.   

    比較少是什麼概念呢?
    就算小於10吧select [name],counts from T where counts>=10
    union
    select 'other',sum(counts) from T where counts<10
      

  4.   

    就是除了前3位数据最多的,剩余的都算在other里
      

  5.   

    如果数据就是那样的,各位的结果都是正确的.不过这些数据是变化的,就是说,a,b,c不一定就是前三位数据,只是从表中取最前三位数据,剩余的都算在other里.
      

  6.   

    --借用一下,简单点的select [name],counts from T where name in (select top 3 name from T order by counts desc)
    union
    select 'other',sum(counts) from T where name not in (select top 3 name from T order by counts desc)
      

  7.   


    現在才明白你前三的意思,開始以為你是指上面那個示例數據的前三條,沒想到是說表中的前三條。:)Create Table TEST
    (id Int,
     name Varchar(10),
     counts Int)
    Insert TEST Select 1,       'a',      34
    Union All Select 2,       'b',      56
    Union All Select 3,       'c',      24
    Union All Select 4,       'd',       2
    Union All Select 5,       'e',       1
    Union All Select 6,       'f',       3
    GO
    Select 
    name,
    SUM(counts) As counts
    From 
    (Select 
    (Case When counts In (Select TOP 3 counts From TEST Order By counts Desc) Then name Else 'Other' End) As name,
    counts
    From TEST) A
    Group By name
    GO
    Drop Table TEST
    --Result
    /*
    id counts
    a 34
    b 56
    c 24
    Other 6
    */
      

  8.   

    select name , counts
    from tab where counts > 10
    union 
    select other as name , sum(counts)
    from tab where counts < 10
      

  9.   

    select name , counts
    from tab where counts in (select top 3 counts from tab order by counts asc )
    union 
    select other as name , sum(counts)
    from tab where counts not in  (select top 3 counts from tab order by counts asc )
      

  10.   

    发表时间:  2006-07-14 08:18:16  zjdyzwx(十一月猪) ( ) 信誉:100  2006-07-14 11:34:00