有一张表(购物表)
商品类型  用户类型(类型1,类型2,类型3)
现要统计购买某种商品总用户数,以及每种用户类型的用户数:
商品类型   总用户数   类型1   类型2  类型3
能用一条SQL语句实现吗?dbexpress+mysql+linux

解决方案 »

  1.   

    select 商品类型,a.sa,b.sb,c.sc from 购物表
    left join
    (select 商品类型,sum(用户数) as sa from ... where 用户类型=类型1 group by 商品类型) a
        on (购物表.商品类型 = a.商品类型)
    left join
    (select 商品类型,sum(用户数) as sb from ... where 用户类型=类型2 group by 商品类型) b
        on (购物表.商品类型 = b.商品类型)
    left join
    (select 商品类型,sum(用户数) as sc from ... where 用户类型=类型3 group by 商品类型) c
        on (购物表.商品类型 = c.商品类型)
      

  2.   

    select f.商品类型,f.type1+f.type2+f.type3 as '总用户数',f.type1 as '类型1',f.type2 as '类型2',f.type3 as '类型3' from(select 商品类型,sum(case value2 when '类型1' then 1 else 0 end) as ,sum(case value2 when '类型2' then 1 else 0 end) as type2,sum(case value2 when '类型3' then 1 else 0 end) as type3 from #kkk group by 商品类型)f