Id Item
--------------
1 ItemA
2 ItemB
3 ItemC
itemid Price
----------------
1 4
1 3
1 9
2 2
2 4
2 3
如何從2個表中選擇總和?就像爲:從SQL Server中的表中選擇加入和總和
ItemA 16
ItemB 9
ItemC 0
Id Item
--------------
1 ItemA
2 ItemB
3 ItemC
itemid Price
----------------
1 4
1 3
1 9
2 2
2 4
2 3
如何從2個表中選擇總和?就像爲:從SQL Server中的表中選擇加入和總和
ItemA 16
ItemB 9
ItemC 0
您可以使用LEFT JOIN
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
@MahmoudGamal謝謝 – SRIRAM
有什麼樣的表之間的參照鍵,如主鍵/外鍵。 – ankur