帮忙看看这个SQL怎么写

cutesun 2003-07-01 03:47:01
Table1
==========================
用户名 消费种类
--------------------------
aaa 1
aaa 2
bbb 1
bbb 1
bbb 1
==========================

Table2
==========================
用户名 性别
--------------------------
aaa 男
bbb 女
==========================

表里的数据量都比较大
怎样能比较高效的算出
===================================
用户名 消费1的次数 消费2的次数
-----------------------------------
aaa 1 1
bbb 3 0
===================================
谢谢!
...全文
57 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
dafu71 2003-07-01
  • 打赏
  • 举报
回复
select *,(select count(*) from table1 where 消费种类=1 and 用户名=table2.用户名) 消费1的次数,(select count(*) from table1 where 消费种类=2 and 用户名=table2.用户名) 消费2的次数 from table2
wycg_cnh20 2003-07-01
  • 打赏
  • 举报
回复
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.用户名,性别
sidshen 2003-07-01
  • 打赏
  • 举报
回复
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 用户名
星星 2003-07-01
  • 打赏
  • 举报
回复
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 用户名
CrazyFor 2003-07-01
  • 打赏
  • 举报
回复
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 用户名
CrazyFor 2003-07-01
  • 打赏
  • 举报
回复
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 用户名

ben988211 2003-07-01
  • 打赏
  • 举报
回复
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
pengdali 2003-07-01
  • 打赏
  • 举报
回复
select *,(select count(*) from table1 where 消费种类=1 and 用户名=table2.用户名) 消费1的次数,(select count(*) from table1 where 消费种类=2 and 用户名=table2.用户名) 消费2的次数 from table2
cutesun 2003-07-01
  • 打赏
  • 举报
回复
错了一点 结果是
===================================
用户名 性别 消费1的次数 消费2的次数
-----------------------------------
aaa 男 1 1
bbb 女 3 0
===================================

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧