在 SQL Server 中使用 Sum Aggregate 函数进行内部联接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6411202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:03:31  来源:igfitidea点击:

Inner Join with Sum Aggregate function in SQL Server

sqlsql-server-2005sumaggregate-functionsinner-join

提问by thevan

I have three tables StockSummary, Item, ItemSpecification. Here I want to join these three tables and to get Sum(StockSummary.Quantity). The main Columns are as follows:

我有三个表 StockSummary、Item、ItemSpecification。这里我想加入这三个表并得到 Sum(StockSummary.Quantity)。主要栏目如下:

TableA: StockSummary(ItemID, Quantity)
TableB: Item(ItemID, ItemName, SpecificationID)
TableC: ItemSpecification(SpecificationName, SpecificationID)

The desired result should give ItemName, SpecificationName and SUM(Quantity). How to use Aggregate function in Inner Joins?

所需的结果应提供 ItemName、SpecificationName 和 SUM(Quantity)。如何在内部联接中使用聚合函数?

回答by Alex K.

You aggregate the desired column & group by the remainder, the fact that the columns are from the result of a join is not relevant in your case;

您按余数聚合所需的列和组,列来自连接结果的事实与您的情况无关;

select
   b.ItemName,
   c.SpecificationName,
   sum(a.Quantity)
from
   tablea a
   inner join tableb b on b.ItemID = a.ItemID
   inner join tablec c on c.SpecificationID = b.SpecificationID
group by
   b.ItemName,
   c.SpecificationName