0
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
4

3 回答 3

3

您可以JOIN使用 a 表格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

请参阅带有演示的 SQL Fiddle

LEFT JOIN将允许不在第二个表中的记录包含在最终结果中。我添加了IsNull()以用零sum()替换任何值。null

结果:

|  ITEM | TOTAL |
-----------------
| ItemA |    16 |
| ItemB |     9 |
| ItemC |     0 |
于 2012-11-20T11:16:00.663 回答
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
于 2012-11-20T11:16:00.860 回答
1

试试这个

select item,sum(price) from table1 left outer join table2 
 on table1.id=table2.itemid
 group by item
于 2012-11-20T11:17:34.057 回答