【问题标题】:Selection with join and sum from table in SQL Server从 SQL Server 中的表中使用连接和求和进行选择
【发布时间】:2012-11-20 19:33:32
【问题描述】:
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

【问题讨论】:

  • 表之间是否有任何类型的引用键,如主键/外键。

标签: sql algorithm


【解决方案1】:

您可以使用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

SQL Fiddle with Demo

LEFT JOIN 将允许不在第二个表中的记录包含在最终结果中。我将IsNull() 添加到sum() 以用零替换任何null 值。

结果:

|  ITEM | TOTAL |
-----------------
| ItemA |    16 |
| ItemB |     9 |
| ItemC |     0 |

【讨论】:

    【解决方案2】:

    试试这个

    select item,sum(price) from table1 left outer join table2 
     on table1.id=table2.itemid
     group by item
    

    【讨论】:

      【解决方案3】:

      请尝试:

      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
      

      【讨论】:

        猜你喜欢
        • 2019-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-20
        • 2014-04-14
        • 2018-09-01
        • 2020-04-05
        相关资源
        最近更新 更多