ID项目
--------------
1意达
2 ItemB
3 ItemC
itemid的价格
----------------
1 4
1 3
1 9
2 2
2 4
2 3
我怎么能与金额从2表选择?像为:
意达16
ItemB 9
ItemC 0
解决方案
可以加入
使用左表连接
并应用聚合函数 SUM()
到价格
字段:
选择t1.item,ISNULL(SUM(t2.price),0)共
从表1 T1
左连接表2 T2
在t1.id = t2.itemid
按t1.item
请参阅 SQL拨弄演示
在 LEFT JOIN
将允许不在第二个表将包含在最终结果中的记录。我加了 ISNULL()
到和()
来更换任何空
值以零。
结果:
|项目|总计|
-----------------
|意达| 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
How I can select with sum from 2 tables? Like as:
ItemA 16
ItemB 9
ItemC 0
解决方案
You can JOIN
the table using a LEFT JOIN
and apply an aggregate function SUM()
to the price
field:
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
See SQL Fiddle with Demo
The LEFT JOIN
will allow for the records not in the second table to be included in the final result. I added the IsNull()
to the sum()
to replace any null
values with a zero.
Result:
| ITEM | TOTAL |
-----------------
| ItemA | 16 |
| ItemB | 9 |
| ItemC | 0 |
上一篇:统一散列函数函数、统一散列
下一篇:树删除节点节点