简体   繁体   English

带有查询和分组依据的 SQL Sum

[英]SQL Sum with query and Group by

I have 2 tables:我有2张桌子:

在此处输入图片说明

like this and would like to count bill on tblsoinvoiceheader with sum on sub query by condition on ProductCode = Discount-1000像这样,并希望通过 ProductCode = Discount-1000 上的条件来计算 tblsoinvoiceheader 上的账单和子查询的总和

What kind of query should I have?我应该有什么样的查询?

To prepare data in tblsoinvoiceheader we need to use such query:要在tblsoinvoiceheader准备数据,我们需要使用这样的查询:

select TransactionDate, 
       count(*) CountOfBill, 
       sum(InvoiceAmountWithTax) InvoiceAmountWithTax 
from tblsoinvoiceheader
group by TransactionDate

and then join it with result of below query:然后将其与以下查询的结果连接:

select (-1)*LineAmountWithTax
from tblsoinvoiceitem
where ProductCode = 'Discount-1000'

Summing up:加起来:

select * from (
    select (-1)*LineAmountWithTax
    from tblsoinvoiceitem
    where ProductCode = 'Discount-1000'
-- i used cross join because you didn't specify joining condition and it looks like you want to 
-- join all recrods
) a cross join (
    select TransactionDate, 
           count(*) CountOfBill, 
           sum(InvoiceAmountWithTax) InvoiceAmountWithTax 
    from tblsoinvoiceheader
    group by TransactionDate
) b

If you have at most one DISCOUNT line per invoice, then you can use:如果每张发票最多有一个DISCOUNT行,则可以使用:

SELECT h.TransactionDate,
       COUNT(*) AS CountOfBill,
       SUM(h.InvoiceAmountWithTax) AS InvoiceAmountWithTax,
       SUM(CASE WHEN i.Remark = 'Discount' THEN -i.LineAmountWithTax END) AS Discount
FROM tblsoinvoiceheader h LEFT JOIN
     tblsoinvoiceitem i
     ON i.DocNo = h.DocNo AND
        i.Remark = 'Discount'
GROUP BY h.TransactionDate;

If you can have multiple discounts per doc, then you need to pre-aggregate.如果每个文档可以有多个折扣,则需要预先汇总。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM