SQL联接查询
待操作表结构
A表:people
id name
01 张三
02 赵四
B表: count
id countfield1 countfield2
01 15 -1
02 10 0
01 1 0
01 2 0
02 5 0
得到一个表以统计同名字的countfield1及countfield2字段值的总和,即如下所示
name countfield
张三 17
赵四 15
如何写SQL查询语句得到或如何写存储过程以供调用?
我写了如下视图:vCount
select A.Name,B.CountField1,B.countField2
from people A inner join Count B on
A.ID=B.ID
然后用如下语句调用的时候出错:
Select Name,sum(CountField1+CountField2) from vCount
为什么出错,如何解决?
------解决方案--------------------Select Name,sum(CountField1+CountField2) from vCount group by Name
------解决方案--------------------create table A(id varchar(10), name varchar(10))
insert into A values( '01 ', '张三 ')
insert into A values( '02 ', '赵四 ')
create table B(id varchar(10), countfield1 int, countfield2 int)
insert into B values( '01 ', 15,-1)
insert into B values( '02 ', 10,0)
insert into B values( '01 ', 1 ,0)
insert into B values( '01 ', 2 ,0)
insert into B values( '02 ', 5 ,0)
select A.name , sum(B.countfield1 + B.countfield2) countfield
from A,B
where A.id = b.id
group by name
drop table A,B
/*
name countfield
---------- -----------
张三 17
赵四 15
(所影响的行数为 2 行)
*/
------解决方案--------------------create procedure GetAll
as
begion
Select
Name,
sum(CountField1+CountField2)
from vCount g
roup by Name
end