按产品ID获取数量总和

时间:2012-12-01 14:26:57

标签: c# sql sql-server

我很难从我的数据库中获得一些结果。我有一张这样的桌子:

    ID ID_INVOICE PRODUCT QUANTITY PRODUCT_ID
    ------------------------------------------
     1    1          aaa     3       2
     2    1          bbb     2       3
     3    1          ccc     1       4
     4    2          bbb     3       3
     5    2          aaa     3       2

所以在查询之后我想得到像

这样的东西
   aaa  6
   bbb  5
   ccc  1

该查询基于ID_INVOICE到目前为止我已尝试过:

  SELECT product, sum(quantity) 
  FROM product 
  WHERE invoice_id = @p1

1 个答案:

答案 0 :(得分:4)

添加GROUP BY product子句,如下所示:

SELECT  product, sum(quantity) 
FROM product 
WHERE invoice_id = @p1
GROUP BY product;

SQL Fiddle Demo