SQL语句怎么写下面的统计?
假设有以下11条记录(两个字段,用户,电费):
用户:User1,User2,User3,User3,User4,User5,User6,User7,User8,User9,User10,User11
电费:2,34,56,12,44,3,9,8,44,23,67
我想达到分段统计电费,如0-20为一段,21-40为一段,41-60为一段,61以上为一段
结果如下:上面四段以A,B,C,D表示
分段   统计 
 A       5
 B       2
 C       3
 D       1

解决方案 »

  1.   

    如果是sql server,用case关键字。
      

  2.   

    select 'a' as 分段, count(用户) where 电费<=20 union all select 'b' as 分段, count(用户) where 电费>20 and 电费<=40 union all select 'c' as 分段, count(用户) where 电费>40 and 电费<=60 union all select 'd' as 分段, count(用户) where 电费>60
      

  3.   

    select 'A', count(*) from table1
    where 筿禣 between 0 and 20
    union
    select 'B', count(*) from table1
    where 筿禣 between 21 and 40
    union
    select 'C', count(*) from table1
    where 筿禣 between 41 and 60
    union
    select 'D', count(*) from table1
    where 筿禣 > 60
      

  4.   

    对不起,少了(from 表) 请加在每一个 where 前
      

  5.   

    不用case的话一次查询恐怕不行。
      

  6.   

    要是access,有点麻烦:
    select iif(电费<=20,A,iif(电费<=40,B,iif(...))) as 分段,count(分段) as 统计 from tablename group by iif(电费<=20,A,iif(电费<=40,B,iif(...)))
      

  7.   

    select 'A', count(*) from table1
    where 电费 between 0 and 20
    union
    select 'B', count(*) from table1
    where 电费 between 21 and 40
    union
    select 'C', count(*) from table1
    where 电费 between 41 and 60
    union
    select 'D', count(*) from table1
    where 电费 > 60这样写容易懂
      

  8.   

    我想 wynbfqny(今无心) 写得不错,用union来将分别查询并起来成为一个记录集。
      

  9.   

    select 'A' as 分段, count(*) as 統計 from  表名
    where 電費 >= 0 and 電費 <=20
    union
    select 'B' as 分段, count(*) as 統計  from  表名
    where  電費 >= 21 and 電費 <=40
    union
    select 'C' as 分段, count(*) as 統計  from  表名
    where 電費 >= 41 and 電費 <=60
    union
    select 'D' as 分段, count(*) as 統計  from  表名
    where 電費 >= 61這樣寫才是對的.
      

  10.   

    还可以在表里面加一个字段
    用来记录A,B,C,D