按分组设置分组,但不包括所有选定的列

时间:2015-04-30 15:34:05

标签: sql-server

我有4列:AccountNumber,Company,Batch和Amount。我希望按公司和批次计算(金额),而不是按帐户编号,因为AccountNumber始终是唯一的,这不会真正完成任何事情。有没有办法使用分组集来按公司和批次汇总(金额)而不是按帐户编号汇总,同时仍然在结果集中显示帐户编号?

谢谢

2 个答案:

答案 0 :(得分:0)

是的,这类问题需要子查询和连接。如果我们将问题视为两个步骤,那么很容易理解:

这将按公司和批次加总:

select company, batch, sum(amount) as sum_amount
from atable
group by company, batch

现在只需将其加入您的帐号

即可
select atable.accountnumber, subq.company, subq.batch, subq.sum_amount
from (
    select company, batch, sum(amount) as sum_amount
    from atable
    group by company, batch
) subq
join atable on subq.company = atable.company and subq.batch = atable.batch

答案 1 :(得分:0)

select b.Company, b.Batch, b.AccountNumber, s.Total
from baseTable b
inner join
(
    select Company, Batch, sum(Amount) Total
    from basetable
    group by Company, Batch
) s on s.Company = b.Company and s.Batch = b.Batch

这样做,但确实给出了每一行的总数。但是,没有任何方法可以阻止这种情况。