选择与连接,并从表中的SQL Server总结并从、SQL、Server

2023-09-11 23:28:46 作者:君踏桃花归

  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
 

解决方案 配置Oracle透明网关用以连接 SQLServer经验总结

可以加入使用左表连接并应用聚合函数 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 |