获取总和的 SQL 语法问题
好吧,我有两张桌子。
表 IDAssoc 具有列bill_id
、year
、area_id
。
表 Bill 具有列 bill_id
、year
、main_id
和 amount_due
。
我试图从账单表中获取 IDAssoc 表中每个关联的 area_ids 的 amount_due
列的总和。
我正在执行一个 select 语句来选择总和并加入 bill_ids。我该如何设置,以便关联表中每个area_id 中的每个关联账单都有一行。每个 area_id 可能有三个或四个 bill_id 关联,我需要将每个 bill_id 相加并返回,以便我可以在另一个语句中使用此选择。我为area_id设置了一个group by,但它仍然返回每一行,而不是为每个area_id汇总它们。我已经在 where 子句中指定了年份和 main_id 以返回我想要的数据,但我无法使总和正常工作。抱歉,我仍在学习,我不知道该怎么做。谢谢!
编辑-基本上,到目前为止我正在尝试的查询基本上就像下面发布的查询一样:
select a.area_id, sum(b.amount_due)
from IDAssoc a
inner join Bill b
on a.bill_id = b.bill_id
where Bill.year = 2006 and bill.bill_id = 11111
这些只是任意数字。 返回的数据是这样的: 应付金额 - 区域 ID .05 1003 .15 1003 .11 1003 65 1004 55 1004
我需要为每个area_id 返回一行,并将amount_due 相加。 area_id仅存在于assoc表中,而不存在于bill表中。
Ok I have two tables.
Table IDAssoc has the columnsbill_id
, year
, area_id
.
Table Bill has the columns bill_id
, year
, main_id
, and amount_due
.
I'm trying to get the sum of the amount_due
column from the bill table for each of the associated area_ids in the IDAssoc table.
I'm doing a select statement to select the sum and joining on the bill_ids. How can I set this up so it will have a single row for each of the associated bills in each area_id from the assoc table. There may be three or four bill_ids associated with each area_id and I need those summed for each and returned so I can use this select in another statement. I have a group by set up for the area_id but it still is returning each row and not summing them up for each area_id. I have the year and main_id specified already in the where clause to return the data that I want, but I can't get the sum to work properly. Sorry I'm still learning and I'm not sure how to do this. Thanks!
Edit- Basically the query I'm trying so far is basically just like the one posted below:
select a.area_id, sum(b.amount_due)
from IDAssoc a
inner join Bill b
on a.bill_id = b.bill_id
where Bill.year = 2006 and bill.bill_id = 11111
These are just arbitrary numbers.
The data this is returning is like this:
amount_due - area_id
.05 1003
.15 1003
.11 1003
65 1004
55 1004
I need one row returned for each area_id with the amount_due summed. The area_id is only in the assoc table and not in the bill table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果一个
IDAssoc
可以有多个或没有Bill
,您可能需要将inner join
更改为left join
:You might want to change
inner join
toleft join
if oneIDAssoc
can have many or noBill
:您缺少
GROUP BY
子句:You are missing the
GROUP BY
clause: