• 全部
  • 问答

升级下,4个表联合查询

AVAmyZ 2011-12-28 01:25:13
现有2个表:
A表:
id c_name
1 a客户
2 b客户
3 c客户
====================
B表(customer_id就是a表的id):
id customer_id project_type
1 1 JH
2 1 HT
3 1 FW
4 1 HT
5 2 JH
......
====================================
C表(customer_id就是a表的id)
id customer_id other
1 1 xxxx
2 1 yyy
3 2 zzzzzz
=================================
D表(customer_id就是a表的id)
id customer_id other
1 1 xxxx
2 1 yyy
3 2 zzzzzz
4 2 wwww
=================================
现需要做联合查询,得出类似与下面的数据列
客户名称 JH HT FW C表统计数 D表统计数
a客户 1个 2个 1个 2个 2个
b客户 1个 0个 0个 1个 2个
=======================================
也就是说不单单是要统计客户的 project_type 数量,而且还要得出每个类型(已固定只有三种类型)的具体数量 ,以及C表和D表中的统计数,这个sql应该怎么写??请大大门赐教啊~~~~~~~~~~~~~~~~~~~~~~~~
...全文
44 点赞 收藏 2
写回复
2 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
ACMAIN_CHM 2011-12-28
select a.c_name,
sum(if(project_type='JH',1,0)) as JH,
sum(if(project_type='HT',1,0)) as HT,
sum(if(project_type='FW',1,0)) as FW,
c1.cnt,
d1.cnt
from a inner join b on a.id=b.customer_id
left join (select customer_id,count(*) as cnt from C group by customer_id) c1 on a.id=c1.customer_id
left join (select customer_id,count(*) as cnt from D group by customer_id) d1 on a.id=d1.customer_id
group by a.c_name
回复
wwwwb 2011-12-28
select a.c_name,
sum(if(project_type='JH',1,0)) AS JH,
sum(if(project_type='HT',1,0)) AS HT,
sum(if(project_type='FW',1,0)) AS FW,
COUNT(*) AS 合计,
(SELECT COUNT(*) FROM C WHERE a.id=customeR_ID) AS C表统计数,
(SELECT COUNT(*) FROM D WHERE a.id=customeR_ID) AS D表统计数

from a inner join b on a.id=b.customer_id
group by a.c_name
回复
相关推荐
发帖
MySQL
创建于2007-09-28

5.5w+

社区成员

MySQL相关内容讨论专区
申请成为版主
帖子事件
创建了帖子
2011-12-28 01:25
社区公告
暂无公告