很简单的问题。我想要做的是从一个表中选择所有列,并从另一个表中选择一列(可能有多个匹配行)的总和。
示例:
table ta (eid, uid, name, year, etc, etc, etc)
table tb (eid, uid, name, year, amount, etc, etc)
eid
- 两个表之间不匹配
uid、姓名、年份
- 将在两个表中匹配
所以我想从表ta
中取出所有列,简单:
select * from ta where eid='value';
我想将表tb
中的金额列连接到我的结果集,简单:
select a.*, b.amount
from ta a
inner join tb b on a.year=b.year
where a.eid='value';
太好了,这很好用。但是如果表 tb 中有多行怎么办?
执行:
select a.*, sum(b.amount)
from ta a inner join tb b on a.uid=b.uid
where a.year='value';
给我以下错误:
Column 'ta.eid' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
所以我补充一下:
select a.*, sum(b.amount)
from ta a inner join tb b on a.uid=b.uid
where a.year='value' group by ta.uid;
我也遇到同样的错误!
但是,如果我将查询更改为:
select a.uid, a.year, sum(b.amount)
from ta a inner join tb b on a.uid=b.uid
where a.year='value'
group by ta.uid, ta.year;
它有效,但现在我有三列,而不是我想要的所有列。
所以,此时我的问题变成:除了手动输入我想要使用 GROUP BY 子句从两个表中提取的所有列之外,是否有更好、更清晰的方式来构造此查询?
最佳答案
您可以在子查询中预聚合:
select a.*, b.sumb
from ta a left join
(select b.uid, sum(b.amount) as sumb
from tb b
group by b.uid
) b
on a.uid=b.uid
where a.year = 'value';
关于sql - 多表连接与聚合(mssql/sql server),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24241869/