表的数据如下:
名称  重量
A      20
B      30
C      30
A      25
C      50
我想做一个归类统计大于40,和小于40的
结果
名称   大于40  小于40
A       2        0
B       1        0
C       1        1
请问sql语句怎么写?谢谢

解决方案 »

  1.   

    --> 测试数据:t2
    if object_id('t2') is not null drop table t2---->建表
    create table t2([名称] varchar(1),[重量] int)
    insert t2
    select 'A',20 union all
    select 'B',30 union all
    select 'C',30 union all
    select 'A',25 union all
    select 'C',50
    GO--> 查询结果
    SELECT 名称,
    SUM(case when 重量>=40 then 1 else 0 end) as 大于40 ,
    SUM(case when 重量<40 then 1 else 0 end) as 小于40 
    FROM t2
    group by 名称
    --> 删除表格
    --DROP TABLE t2
    ----
    名称 大于40 小于40
    A 0 2
    B 0 1
    C 1 1
      

  2.   


    select 名称, sum(重量>40) as 大于40 ,sum(重量<40) as 小于40
    From a
    Group by 名称
      

  3.   


    with tb1(name,weight)
    as
    (
    select 'A',20 union
    select 'B',30 union
    select 'C',30 union
    select 'A',25 union
    select 'C',50
    )
    select name,
    sum(case when weight>40 then 1 else 0 end) as '大于40',
    sum(case when weight<=40 then 1 else 0 end) as '小于40'
    from tb1
    group by name--结果--A 0 2
    --B 0 1
    --C 1 1
      

  4.   

    运行时候提示“查询设计器不支持 CASE SQL 构造”,请问还有什么方法解决
      

  5.   

    SELECT 
      名称,
      SUM(case when 重量>=40 then 1 else 0 end) as 大于40 ,
      SUM(case when 重量<40 then 1 else 0 end) as 小于40 
    FROM 
      t2
    group by 
      名称