从SQL Server中的表中选择连接和求和

时间:2012-11-20 11:12:11

标签: sql algorithm

Id       Item
--------------
1        ItemA 
2        ItemB
3        ItemC

itemid     Price
----------------
1          4
1          3
1          9
2          2
2          4
2          3

如何从2张表中选择总和?像:

ItemA 16
ItemB 9
ItemC 0

3 个答案:

答案 0 :(得分:3)

您可以使用JOIN LEFT JOIN使用SUM()并将汇总函数price应用于select t1.item, IsNull(sum(t2.price), 0) total from table1 t1 left join table2 t2 on t1.id = t2.itemid group by t1.item 字段:

LEFT JOIN

请参阅SQL Fiddle with Demo

IsNull()将允许不在第二个表中的记录包含在最终结果中。我将sum()添加到null,将所有| ITEM | TOTAL | ----------------- | ItemA | 16 | | ItemB | 9 | | ItemC | 0 | 值替换为零。

结果:

{{1}}

答案 1 :(得分:1)

请尝试:

select a.Item, ISNULL(SUM(b.Price), 0) AS TOTALSum
from Table1 a LEFT JOIN Table2 b on a.Id=b.ItemId
Group by a.Item

答案 2 :(得分:1)

试试这个

select item,sum(price) from table1 left outer join table2 
 on table1.id=table2.itemid
 group by item