选择与连接,并从表中的SQL Server总结 [英] Selection with join and sum from table in SQL Server
本文介绍了选择与连接,并从表中的SQL Server总结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
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 |
这篇关于选择与连接,并从表中的SQL Server总结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文