现在有TABLE表中有5个字段,
分别是ID,name,price,num
其中price的值是1或者2
现在想得到查询结果:
name,price=1时的sum(num)值,price=2时的sum(num)值
请问这个语句应该怎么写啊?

解决方案 »

  1.   

    select name,sum(num) from tb
    group by name,price
    order by name,price
      

  2.   

    select name,sum(case price when 1 then num else 0 end) as num1,sum(case price when 2 then num else 0 end) as num2
    from table
    group by name
      

  3.   

    select name,sum(case price when 1 then num else 0 end) as num1,sum(case price when 2 then num else 0 end) as num2
    from table
    group by name
      

  4.   

    如果结果格式为
    ID,name,price,sum(num=1),sum(num=2)的话,3楼的正解如果为
    ID,name,price,num
    ^^^^^^          sum(num=1)
    ………………………sum(num=2)
    的话select ID,name,price,sum(num)
    from tb
    where num=1
    union
    select ID,name,price,sum(num)
    from tb
    where num=2
      

  5.   


    select name,sum(case when price=1 then num else 0 end) as price1, sum(case when price=2 then num else 0 end) as price2 from table group by name
      

  6.   

    select 
    name,
    (select sum(num) from tb where  price=1 and name=a.name),
    (select sum(num) from tb where  price=2 and name=a.name)
    from tb a
    group by name