如何获得链接到一个单元格的许多单元格的总和

时间:2017-10-27 16:04:19

标签: sql sql-server sql-server-2012

我尝试创建一个查询,该查询返回发票上已售商品的总费用。我已经尝试过各种各样的求和方法,但不能得到它背后的逻辑。

select 
    Concat(invoiceNum, '-', invoiceSubNum) as 'invoice',
    itemCost                                     
from tbl_invoiceItem 
group by 
    invoiceNum, invoiceSubNum, sku, 
    itemCost, itemPrice, itemDiscount, 
    percentage
order by invoiceNum

目前输出的数据:

 Invoice | itemCost
 1-1     | 60
 1-1     | 5
 2-1     | 25
 3-1     | 10
 3-1     | 5

我想要输出的内容:

 Invoice | totalCost
 1-1     | 65
 2-1     | 25
 3-1     | 15

创建#temp表是否可能成为解决方案?

1 个答案:

答案 0 :(得分:2)

您需要SUM发票中的所有费用

select 
    Concat(invoiceNum, '-', invoiceSubNum) as 'invoice',
    SUM(itemCost)
from tbl_invoiceItem 
group by 
    Concat(invoiceNum, '-', invoiceSubNum)
order by invoiceNum