简体   繁体   English

带WHERE子句的嵌套SQL SUM

[英]Nested SQL SUM with WHERE Clause

I am trying to calculate cost of items sold in a day and total discount given in a day. 我正在尝试计算一天中售出商品的成本以及一天中给出的总折扣。

Table Structure is 表格结构为

sale Table
invoice_no | bill_date | discount | ...

The child table is (invoice_no is FK with sale table) 子表是(invoice_no是带销售表的FK)

sale_items Table
invoice_no | item_no | cost_price | qty

This query works fine 这个查询工作正常

SELECT (SELECT SUM(p.cost_price*p.qty) FROM sale_items p
        WHERE p.invoice_no=s.invoice_no) as tcost_amount
 FROM sale s
 WHERE bill_date= '2017-05-26'

but when I want to calculate discount from parent table, tcost_amount sum up all rows in the child table without bill_date criteria, I am confused. 但是,当我想从父表中计算折扣时tcost_amount了不具有bill_date条件的子表中的所有行,我感到困惑。

SELECT SUM(discount), (SELECT SUM(p.cost_price*p.qty)
                       FROM sale_items p
                       WHERE p.invoice_no=s.invoice_no) as tcost_amount
FROM sale s
WHERE bill_date= '2017-05-26'

My question is why bill_date= '2017-05-26' condition is not applying to sale_items in the second case? 我的问题是为什么在第二种情况下bill_date= '2017-05-26'条件不适用于sale_items

At the very least, you need to join the tables. 至少,您需要加入表。 something like this: 像这样的东西:

select (sum(si.cost_price * si.qty) - s.discount)
from sale s
inner join sale_items si on si.invoice_no = s.invoice_no
where s.bill_date = '2017-05-26'

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

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