【问题标题】:SQL Server 2012 add value of rows with matching idsSQL Server 2012 添加具有匹配 id 的行的值
【发布时间】:2015-12-04 15:43:23
【问题描述】:

我正在 SQL Server 2012 上做作业,我必须这样做

7) 创建一个存储过程(称为SQL7),它将检索 慈善机构 ID 和慈善机构名称以及所有捐款总额 每个慈善机构在捐款表中的金额。”

Charity IDCharity Name 在一个表中,第二个表有 CharityIDTotal 贡献。

我不知道如何将每个慈善机构收到的总捐款相加并输出。我到目前为止的代码是

create proc SQL7
as
   select distinct 
       dbo.CharityTbl.CharityID, CharityName,
   from 
       dbo.CharityTbl, dbo.ContributionsTbl
   where 
      dbo.CharityTbl.CharityID = dbo.ContributionsTbl.CharityID

提前致谢!

【问题讨论】:

标签: sql sql-server sql-server-2008 sql-server-2012


【解决方案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/67ccahttp://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 |

【讨论】:

  • 完美运行,非常感谢您的帮助!并感谢其他所有人提供答案!
【解决方案2】:
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 是您的捐款金额字段的名称。

【讨论】:

  • 你为什么要MIN(CharityName)而不是分组呢?
  • 我不确定哪个性能更好,所以我选择在我的代码中看起来更好的那个
【解决方案3】:

你需要了解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

【讨论】:

  • 这不会显示任何会增加总贡献的代码。
  • @isxaker - 我希望在应用更正后,反对者会再次投票。给我点赞。感谢您花时间更新您的答案
【解决方案4】:
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

【讨论】:

  • 将不起作用,因为您没有在前 2 列上提供分组,方括号应为 (...)
  • @ChrisTest - 我希望在应用更正后投票者会再次投票。给我点赞。感谢您花时间更新您的答案
猜你喜欢
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
相关资源
最近更新 更多