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
您可以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
这LEFT JOIN
将允许不在第二个表中的记录包含在最终结果中。我添加了IsNull()
以用零sum()
替换任何值。null
结果:
| ITEM | TOTAL |
-----------------
| ItemA | 16 |
| ItemB | 9 |
| ItemC | 0 |
请试试:
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
试试这个
select item,sum(price) from table1 left outer join table2
on table1.id=table2.itemid
group by item