日期:2014-05-18  浏览次数:20522 次

求助:两表查询,查询公司的时候,顺便把该公司的产品数量统计出来
对不起,两次描述都没有说清楚

两表查询,查询公司的时候,顺便把该公司的产品数量列出来

产品的数量没有在表里存放,是需要统计的,麻烦各位了

公司表 compay

ID gsmc(公司名称)
1 A
2 B
3 C
4 D

产品表 gongying
ID companyID(公司ID)
1 2
2 2
3 4
4 1

查询公司得到表
ID gsmc(公司名称) gsum(该公司产品数量)
1 A 1
2 B 2
3 C 0
4 D 1

------解决方案--------------------
SQL code


select a.id,a.gsmc,count(b.companyId) gsum from company a
left join gongying b on a.id=b.companyId
group by a.id,a.gsmc

------解决方案--------------------
SQL code


Create table #company
(
 id int identity(1,1),
 gsmc nvarchar(50)
)
create table #gongying
(
  id int identity(1,1),
  companyId int
)
insert #company
select 'A' union all
select 'B' union all
select 'C' union all
select 'D' 

insert #gongying
select 2 union all
select 2 union all
select 4 union all
select 1

select a.id,a.gsmc,count(b.companyId) gsum from #company a
left join #gongying b on a.id=b.companyId
group by a.id,a.gsmc

drop table #company,#gongying

--1    A    1
--2    B    2
--3    C    0
--4    D    1