我正在SQL Server 2012上做作业,我必须
7)创建一个将检索的存储过程(称为
SQL7
) 慈善机构ID和慈善机构名称以及所有捐款的总和 每个慈善机构在捐款表中的金额。“
Charity ID
和Charity Name
位于一个表格中,第二个表格包含CharityID
和Total
个。{/ p>
我不知道如何添加每个慈善机构收到的总捐款并将其输出。我到目前为止的代码是
create proc SQL7
as
select distinct
dbo.CharityTbl.CharityID, CharityName,
from
dbo.CharityTbl, dbo.ContributionsTbl
where
dbo.CharityTbl.CharityID = dbo.ContributionsTbl.CharityID
提前致谢!
答案 0 :(得分:1)
您可能需要分组(假设table1保存慈善信息,table2保存贡献信息)
create procedure SQL7
as
select a.charityid, a.charityname, sum(b.totalcontributions) as totals
from CharityTbl a
left join ContributionsTbl b on a.charityid = b.charityid
group by a.charityid, a.charityname
SQLFiddle示例:http://sqlfiddle.com/#!3/67cca和http://sqlfiddle.com/#!3/ca00e
create table charityTbl (charityid int, charityname varchar(100));
insert into charityTbl values (1, 'Red Cross'), (2, 'Doctors without borders');
create table contributionsTbl (charityid int, totalcontributions int);
insert into contributionsTbl values
(1, 100),
(1, 200),
(2, 500);
(只是认为这是一个存储过程,并使用exec SQL7
)
select a.charityid, a.charityname, sum(b.totalcontributions) as totals
from CharityTbl a
left join ContributionsTbl b on a.charityid = b.charityid
group by a.charityid, a.charityname
结果:
| charityid | charityname | totals |
|-----------|-------------------------|--------|
| 2 | Doctors without borders | 500 |
| 1 | Red Cross | 300 |
答案 1 :(得分:0)
您需要了解Join
CREATE PROC SQL7
AS
SELECT
charity.CharityID
,charity.CharityName
SUM(contrib.TotalContrib)
FROM
dbo.CharityTbl AS charity
INNER JOIN dbo.ContributionsTbl AS contrib
ON contrib.CharityID = charity.CharityID
GROUP BY
charity.CharityID
,charity.CharityName
答案 2 :(得分:0)
create proc SQL7
as
SELECT CharityTbl.CharityID,
MIN(CharityName) AS CharityName,
SUM(contribution_amount) AS TotalContribution
FROM CharityTbl
JOIN ContributionsTbl ON CharityTbl.CharityID = ContributionsTbl.CharityID
GROUP BY CharityTbl.CharityID
其中contribution_amount
是您的贡献金额字段的名称。
答案 3 :(得分:0)
Create Proc SQL7
As
Begin
Select CharityID, min(CharityName), Sum(Contributions) as TotalContributions
From
dbo.CharityTbl As Ch
Inner Join
dbo.Contributionstbl as Co
on ch.CharityID = Co.CharityID
group by CharityID
End