错了一点 结果是
===================================
用户名   性别   消费1的次数    消费2的次数
-----------------------------------
aaa       男      1              1
bbb       女      3              0
===================================

解决方案 »

  1.   

    select *,(select count(*) from table1 where 消费种类=1 and 用户名=table2.用户名) 消费1的次数,(select count(*) from table1 where 消费种类=2 and 用户名=table2.用户名) 消费2的次数  from table2
      

  2.   

    select 用户名,性别,
         (select count(1) from Table1 where Table1.用户名 = Table2.用户名 and 消费种类 = 1 ) as 消费1的次数,
         (select count(1) from Table1 where Table1.用户名 = Table2.用户名 and 消费种类 = 2 ) as 消费2的次数
    from Table2
      

  3.   

    select 用户名
      ,sum(case when 消费种类=1 then 1 else 0 end) 消费1的次数
      ,sum(case when 消费种类=2 then 1 else 0 end) 消费2的次数
    from table1
    group by 用户名
      

  4.   

    select 用户名
      ,sum(case when 消费种类=1 then 1 else 0 end) 消费1的次数
      ,sum(case when 消费种类=2 then 1 else 0 end) 消费2的次数
    from table1
    group by 用户名
      

  5.   

    select 用户名
      ,sum(case when 消费种类=1 then 1 else 0 end) 消费1的次数
      ,sum(case when 消费种类=2 then 1 else 0 end) 消费2的次数
    from table1
    group by 用户名
      

  6.   

    select 用户名
      ,sum(case when 消费种类=1 then 1 else 0 end) 1的次数
      ,sum(case when 消费种类=2 then 1 else 0 end) 2的次数
      ,sum(case when 消费种类=3 then 1 else 0 end) 3的次数
    from table1
    group by 用户名
      

  7.   

    Select table1.用户名,性别,sum(case when 消费种类=1 then 1 else 0 end) 消费1的次数
    ,sum(case when 消费种类=2 then 1 else 0 end) 消费2的次数
    from table1 join table2 on table1.用户名=table2.用户名
    group by  table1.用户名,性别
      

  8.   

    select *,(select count(*) from table1 where 消费种类=1 and 用户名=table2.用户名) 消费1的次数,(select count(*) from table1 where 消费种类=2 and 用户名=table2.用户名) 消费2的次数  from table2