选择所有列值作为总计并乘以

时间:2018-12-01 16:10:08

标签: sql sql-server

这是我的数据库结构:

发票

  • ID

  • 公司

发票行

  • LineID

  • 数量

  • 价格

这些是我的行:

Invoice
ID  Company
1   XYZ
2   ZYX

InvoiceLine
LineID  InvoiceID   quantity    price
1       1           1           10
2       1           5           10

3       2           1           20

我要生成的是动态选择总发票价格:

理想结果

1 XYZ 60
2 ZYX 20

我为此使用以下查询:

select ID, cil.quantity * cil.unitPrice as invoiceTotal from Invoice ci
join InvoiceLine as cil on ci.invoiceID = cil.invoiceID 

问题是此查询为第一张发票返回2行。

这是为什么?如何选择发票行的所有值?

2 个答案:

答案 0 :(得分:1)

您要group by

select ci.id, sum(cil.quantity * cil.unitPrice) as invoiceTotal
from Invoice ci join
     InvoiceLine cil
     on ci.invoiceID = cil.invoiceID 
group by ci.id;

但是,您甚至不需要join

select cil.id, sum(cil.quantity * cil.unitPrice) as invoiceTotal
from InvoiceLine cil
group by cil.id;

答案 1 :(得分:1)

    select Invoice.id,Invoice.Company sum(InvoiceLine.quantity * InvoiceLine.unitPrice) as TotalSum
    from Invoice join
         InvoiceLine cil
         on Invoice.invoiceID = InvoiceLine.invoiceID 
    group by Invoice.id,Invoice.Company

order by Invoice.Company ;